pub struct Connection {
    pub connection: DbConnection,
    pub(crate) conf: Configuration,
}
Expand description

A connection to a mailpot database.

Fields§

§connection: DbConnection

The rusqlite connection handle.

§conf: Configuration

Implementations§

source§

impl Connection

source

pub const SCHEMA: &str = _

The database schema.

PRAGMA foreign_keys = true;
PRAGMA encoding = 'UTF-8';

CREATE TABLE IF NOT EXISTS list (
  pk                    INTEGER PRIMARY KEY NOT NULL,
  name                  TEXT NOT NULL,
  id                    TEXT NOT NULL UNIQUE,
  address               TEXT NOT NULL UNIQUE,
  owner_local_part      TEXT,
  request_local_part    TEXT,
  archive_url           TEXT,
  description           TEXT,
  topics                JSON NOT NULL CHECK (json_type(topics) = 'array') DEFAULT '[]',
  created               INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified         INTEGER NOT NULL DEFAULT (unixepoch()),
  verify                BOOLEAN CHECK (verify IN (0, 1)) NOT NULL DEFAULT 1, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  hidden                BOOLEAN CHECK (hidden IN (0, 1)) NOT NULL DEFAULT 0,
  enabled               BOOLEAN CHECK (enabled IN (0, 1)) NOT NULL DEFAULT 1
);

CREATE TABLE IF NOT EXISTS owner (
  pk               INTEGER PRIMARY KEY NOT NULL,
  list             INTEGER NOT NULL,
  address          TEXT NOT NULL,
  name             TEXT,
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS post_policy (
  pk                   INTEGER PRIMARY KEY NOT NULL,
  list                 INTEGER NOT NULL UNIQUE,
  announce_only        BOOLEAN CHECK (announce_only IN (0, 1)) NOT NULL
                       DEFAULT 0, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  subscription_only    BOOLEAN CHECK (subscription_only IN (0, 1)) NOT NULL
                       DEFAULT 0,
  approval_needed      BOOLEAN CHECK (approval_needed IN (0, 1)) NOT NULL
                       DEFAULT 0,
  open                 BOOLEAN CHECK (open IN (0, 1)) NOT NULL DEFAULT 0,
  custom               BOOLEAN CHECK (custom IN (0, 1)) NOT NULL DEFAULT 0,
  created              INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified        INTEGER NOT NULL DEFAULT (unixepoch())
  CHECK((
    (custom) OR ((
    (open) OR ((
    (approval_needed) OR ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  )
  AND NOT
  (
    (approval_needed) AND ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  ))
  )
  AND NOT
  (
    (open) AND ((
    (approval_needed) OR ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  )
  AND NOT
  (
    (approval_needed) AND ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  ))
  ))
  )
  AND NOT
  (
    (custom) AND ((
    (open) OR ((
    (approval_needed) OR ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  )
  AND NOT
  (
    (approval_needed) AND ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  ))
  )
  AND NOT
  (
    (open) AND ((
    (approval_needed) OR ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  )
  AND NOT
  (
    (approval_needed) AND ((
    (announce_only) OR (subscription_only)
  )
  AND NOT
  (
    (announce_only) AND (subscription_only)
  ))
  ))
  ))
  )),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS subscription_policy (
  pk                   INTEGER PRIMARY KEY NOT NULL,
  list                 INTEGER NOT NULL UNIQUE,
  send_confirmation    BOOLEAN CHECK (send_confirmation IN (0, 1)) NOT NULL
                       DEFAULT 1, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  open                 BOOLEAN CHECK (open IN (0, 1)) NOT NULL DEFAULT 0,
  manual               BOOLEAN CHECK (manual IN (0, 1)) NOT NULL DEFAULT 0,
  request              BOOLEAN CHECK (request IN (0, 1)) NOT NULL DEFAULT 0,
  custom               BOOLEAN CHECK (custom IN (0, 1)) NOT NULL DEFAULT 0,
  created              INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified        INTEGER NOT NULL DEFAULT (unixepoch()),
  CHECK((
    (open) OR ((
    (manual) OR ((
    (request) OR (custom)
  )
  AND NOT
  (
    (request) AND (custom)
  ))
  )
  AND NOT
  (
    (manual) AND ((
    (request) OR (custom)
  )
  AND NOT
  (
    (request) AND (custom)
  ))
  ))
  )
  AND NOT
  (
    (open) AND ((
    (manual) OR ((
    (request) OR (custom)
  )
  AND NOT
  (
    (request) AND (custom)
  ))
  )
  AND NOT
  (
    (manual) AND ((
    (request) OR (custom)
  )
  AND NOT
  (
    (request) AND (custom)
  ))
  ))
  )),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS subscription (
  pk                      INTEGER PRIMARY KEY NOT NULL,
  list                    INTEGER NOT NULL,
  address                 TEXT NOT NULL,
  name                    TEXT,
  account                 INTEGER,
  enabled                 BOOLEAN CHECK (enabled IN (0, 1)) NOT NULL
                          DEFAULT 1, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  verified                BOOLEAN CHECK (verified IN (0, 1)) NOT NULL
                          DEFAULT 1,
  digest                  BOOLEAN CHECK (digest IN (0, 1)) NOT NULL
                          DEFAULT 0,
  hide_address            BOOLEAN CHECK (hide_address IN (0, 1)) NOT NULL
                          DEFAULT 0,
  receive_duplicates      BOOLEAN CHECK (receive_duplicates IN (0, 1)) NOT NULL
                          DEFAULT 1,
  receive_own_posts       BOOLEAN CHECK (receive_own_posts IN (0, 1)) NOT NULL
                          DEFAULT 0,
  receive_confirmation    BOOLEAN CHECK (receive_confirmation IN (0, 1)) NOT NULL
                          DEFAULT 1,
  last_digest             INTEGER NOT NULL DEFAULT (unixepoch()),
  created                 INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified           INTEGER NOT NULL DEFAULT (unixepoch()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE,
  FOREIGN KEY (account) REFERENCES account(pk) ON DELETE SET NULL,
  UNIQUE (list, address) ON CONFLICT ROLLBACK
);

CREATE TABLE IF NOT EXISTS account (
  pk               INTEGER PRIMARY KEY NOT NULL,
  name             TEXT,
  address          TEXT NOT NULL UNIQUE,
  public_key       TEXT,
  password         TEXT NOT NULL,
  enabled          BOOLEAN CHECK (enabled IN (0, 1)) NOT NULL DEFAULT 1, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS candidate_subscription (
  pk               INTEGER PRIMARY KEY NOT NULL,
  list             INTEGER NOT NULL,
  address          TEXT NOT NULL,
  name             TEXT,
  accepted         INTEGER UNIQUE,
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE,
  FOREIGN KEY (accepted) REFERENCES subscription(pk) ON DELETE CASCADE,
  UNIQUE (list, address) ON CONFLICT ROLLBACK
);

CREATE TABLE IF NOT EXISTS post (
  pk               INTEGER PRIMARY KEY NOT NULL,
  list             INTEGER NOT NULL,
  envelope_from    TEXT,
  address          TEXT NOT NULL,
  message_id       TEXT NOT NULL,
  message          BLOB NOT NULL,
  headers_json     TEXT,
  timestamp        INTEGER NOT NULL DEFAULT (unixepoch()),
  datetime         TEXT NOT NULL DEFAULT (datetime()),
  created          INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS template (
  pk               INTEGER PRIMARY KEY NOT NULL,
  name             TEXT NOT NULL,
  list             INTEGER,
  subject          TEXT,
  headers_json     TEXT,
  body             TEXT NOT NULL,
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE,
  UNIQUE (list, name) ON CONFLICT ROLLBACK
);

CREATE TABLE IF NOT EXISTS settings_json_schema (
  pk               INTEGER PRIMARY KEY NOT NULL,
  id               TEXT NOT NULL UNIQUE,
  value            JSON NOT NULL CHECK (json_type(value) = 'object'),
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS list_settings_json (
  pk               INTEGER PRIMARY KEY NOT NULL,
  name             TEXT NOT NULL,
  list             INTEGER,
  value            JSON NOT NULL CHECK (json_type(value) = 'object'),
  is_valid         BOOLEAN CHECK (is_valid IN (0, 1)) NOT NULL DEFAULT 0, -- BOOLEAN FALSE == 0, BOOLEAN TRUE == 1
  created          INTEGER NOT NULL DEFAULT (unixepoch()),
  last_modified    INTEGER NOT NULL DEFAULT (unixepoch()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE,
  FOREIGN KEY (name) REFERENCES settings_json_schema(id) ON DELETE CASCADE,
  UNIQUE (list, name) ON CONFLICT ROLLBACK
);

CREATE TRIGGER
IF NOT EXISTS is_valid_settings_json_on_update
AFTER UPDATE OF value, name, is_valid ON list_settings_json
FOR EACH ROW
BEGIN
  SELECT RAISE(ROLLBACK, 'new settings value is not valid according to the json schema. Rolling back transaction.') FROM settings_json_schema AS schema WHERE schema.id = NEW.name AND NOT validate_json_schema(schema.value, NEW.value);
  UPDATE list_settings_json SET is_valid = 1 WHERE pk = NEW.pk;
END;

CREATE TRIGGER
IF NOT EXISTS is_valid_settings_json_on_insert
AFTER INSERT ON list_settings_json
FOR EACH ROW
BEGIN
  SELECT RAISE(ROLLBACK, 'new settings value is not valid according to the json schema. Rolling back transaction.') FROM settings_json_schema AS schema WHERE schema.id = NEW.name AND NOT validate_json_schema(schema.value, NEW.value);
  UPDATE list_settings_json SET is_valid = 1 WHERE pk = NEW.pk;
END;

CREATE TRIGGER
IF NOT EXISTS invalidate_settings_json_on_schema_update
AFTER UPDATE OF value, id ON settings_json_schema
FOR EACH ROW
BEGIN
  UPDATE list_settings_json SET name = NEW.id, is_valid = 0 WHERE name = OLD.id;
END;

-- # Queues
--
-- ## The "maildrop" queue
--
-- Messages that have been submitted but not yet processed, await processing
-- in the "maildrop" queue. Messages can be added to the "maildrop" queue
-- even when mailpot is not running.
--
-- ## The "deferred" queue
--
-- When all the deliverable recipients for a message are delivered, and for
-- some recipients delivery failed for a transient reason (it might succeed
-- later), the message is placed in the "deferred" queue.
--
-- ## The "hold" queue
--
-- List administrators may introduce rules for emails to be placed
-- indefinitely in the "hold" queue. Messages placed in the "hold" queue stay
-- there until the administrator intervenes. No periodic delivery attempts
-- are made for messages in the "hold" queue.

-- ## The "out" queue
--
-- Emails that must be sent as soon as possible.
CREATE TABLE IF NOT EXISTS queue (
  pk              INTEGER PRIMARY KEY NOT NULL,
  which           TEXT
                  CHECK (
                    which IN
                    ('maildrop',
                     'hold',
                     'deferred',
                     'corrupt',
                     'error',
                     'out')
                  ) NOT NULL,
  list            INTEGER,
  comment         TEXT,
  to_addresses    TEXT NOT NULL,
  from_address    TEXT NOT NULL,
  subject         TEXT NOT NULL,
  message_id      TEXT NOT NULL,
  message         BLOB NOT NULL,
  timestamp       INTEGER NOT NULL DEFAULT (unixepoch()),
  datetime        TEXT NOT NULL DEFAULT (datetime()),
  FOREIGN KEY (list) REFERENCES list(pk) ON DELETE CASCADE,
  UNIQUE (to_addresses, message_id) ON CONFLICT ROLLBACK
);

CREATE TABLE IF NOT EXISTS bounce (
  pk              INTEGER PRIMARY KEY NOT NULL,
  subscription    INTEGER NOT NULL UNIQUE,
  count           INTEGER NOT NULL DEFAULT 0,
  last_bounce     TEXT NOT NULL DEFAULT (datetime()),
  FOREIGN KEY (subscription) REFERENCES subscription(pk) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS post_listpk_idx ON post(list);
CREATE INDEX IF NOT EXISTS post_msgid_idx ON post(message_id);
CREATE INDEX IF NOT EXISTS list_idx ON list(id);
CREATE INDEX IF NOT EXISTS subscription_idx ON subscription(address);

-- [tag:accept_candidate]: Update candidacy with 'subscription' foreign key on
-- 'subscription' insert.
CREATE TRIGGER IF NOT EXISTS accept_candidate AFTER INSERT ON subscription
FOR EACH ROW
BEGIN
  UPDATE candidate_subscription SET accepted = NEW.pk, last_modified = unixepoch()
  WHERE candidate_subscription.list = NEW.list AND candidate_subscription.address = NEW.address;
END;

-- [tag:verify_subscription_email]: If list settings require e-mail to be
-- verified, update new subscription's 'verify' column value.
CREATE TRIGGER IF NOT EXISTS verify_subscription_email AFTER INSERT ON subscription
FOR EACH ROW
BEGIN
  UPDATE subscription
  SET verified = 0, last_modified = unixepoch()
  WHERE
  subscription.pk = NEW.pk
  AND
  EXISTS
  (SELECT 1 FROM list WHERE pk = NEW.list AND verify = 1);
END;

-- [tag:add_account]: Update list subscription entries with 'account' foreign
-- key, if addresses match.
CREATE TRIGGER IF NOT EXISTS add_account AFTER INSERT ON account
FOR EACH ROW
BEGIN
  UPDATE subscription SET account = NEW.pk, last_modified = unixepoch()
  WHERE subscription.address = NEW.address;
END;

-- [tag:add_account_to_subscription]: When adding a new 'subscription', auto
-- set 'account' value if there already exists an 'account' entry with the
-- same address.
CREATE TRIGGER IF NOT EXISTS add_account_to_subscription
AFTER INSERT ON subscription
FOR EACH ROW
WHEN
  NEW.account IS NULL
  AND EXISTS (SELECT 1 FROM account WHERE address = NEW.address)
BEGIN
  UPDATE subscription
     SET account = (SELECT pk FROM account WHERE address = NEW.address),
         last_modified = unixepoch()
    WHERE subscription.pk = NEW.pk;
END;


-- [tag:last_modified_list]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_list
AFTER UPDATE ON list
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE list SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_owner]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_owner
AFTER UPDATE ON owner
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE owner SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_post_policy]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_post_policy
AFTER UPDATE ON post_policy
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE post_policy SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_subscription_policy]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_subscription_policy
AFTER UPDATE ON subscription_policy
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE subscription_policy SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_subscription]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_subscription
AFTER UPDATE ON subscription
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE subscription SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_account]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_account
AFTER UPDATE ON account
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE account SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_candidate_subscription]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_candidate_subscription
AFTER UPDATE ON candidate_subscription
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE candidate_subscription SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_template]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_template
AFTER UPDATE ON template
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE template SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_settings_json_schema]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_settings_json_schema
AFTER UPDATE ON settings_json_schema
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE settings_json_schema SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

-- [tag:last_modified_list_settings_json]: update last_modified on every change.
CREATE TRIGGER
IF NOT EXISTS last_modified_list_settings_json
AFTER UPDATE ON list_settings_json
FOR EACH ROW
WHEN NEW.last_modified == OLD.last_modified
BEGIN
  UPDATE list_settings_json SET last_modified = unixepoch()
  WHERE pk = NEW.pk;
END;

CREATE TRIGGER
IF NOT EXISTS sort_topics_update_trigger
AFTER UPDATE ON list
FOR EACH ROW
WHEN NEW.topics != OLD.topics
BEGIN
  UPDATE list SET topics = ord.arr FROM (SELECT json_group_array(ord.val) AS arr, ord.pk AS pk FROM (SELECT json_each.value AS val, list.pk AS pk FROM list, json_each(list.topics) ORDER BY val ASC) AS ord GROUP BY pk) AS ord WHERE ord.pk = list.pk AND list.pk = NEW.pk;
END;

CREATE TRIGGER
IF NOT EXISTS sort_topics_new_trigger
AFTER INSERT ON list
FOR EACH ROW
BEGIN
  UPDATE list SET topics = arr FROM (SELECT json_group_array(ord.val) AS arr, ord.pk AS pk FROM (SELECT json_each.value AS val, list.pk AS pk FROM list, json_each(list.topics) ORDER BY val ASC) AS ord GROUP BY pk) AS ord WHERE ord.pk = list.pk AND list.pk = NEW.pk;
END;


-- 005.data.sql

INSERT OR REPLACE INTO settings_json_schema(id, value) VALUES('ArchivedAtLinkSettings', '{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$ref": "#/$defs/ArchivedAtLinkSettings",
  "$defs": {
    "ArchivedAtLinkSettings": {
      "title": "ArchivedAtLinkSettings",
      "description": "Settings for ArchivedAtLink message filter",
      "type": "object",
      "properties": {
        "template": {
          "title": "Jinja template for header value",
          "description": "Template for\n        `Archived-At` header value, as described in RFC 5064 \"The Archived-At\n        Message Header Field\". The template receives only one string variable\n        with the value of the mailing list post `Message-ID` header.\n\n        For example, if:\n\n        - the template is `http://www.example.com/mid/{{msg_id}}`\n        - the `Message-ID` is `<0C2U00F01DFGCR@mailsj-v3.example.com>`\n\n        The full header will be generated as:\n\n        `Archived-At: <http://www.example.com/mid/0C2U00F01DFGCR@mailsj-v3.example.com>\n\n        Note: Surrounding carets in the `Message-ID` value are not required. If\n        you wish to preserve them in the URL, set option `preserve-carets` to\n        true.\n        ",
          "examples": [
            "https://www.example.com/{{msg_id}}",
            "https://www.example.com/{{msg_id}}.html"
          ],
          "type": "string",
          "pattern": ".+[{][{]msg_id[}][}].*"
        },
        "preserve_carets": {
          "title": "Preserve carets of `Message-ID` in generated value",
          "type": "boolean",
          "default": false
        }
      },
      "required": [
        "template"
      ]
    }
  }
}');


-- 006.data.sql

INSERT OR REPLACE INTO settings_json_schema(id, value) VALUES('AddSubjectTagPrefixSettings', '{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$ref": "#/$defs/AddSubjectTagPrefixSettings",
  "$defs": {
    "AddSubjectTagPrefixSettings": {
      "title": "AddSubjectTagPrefixSettings",
      "description": "Settings for AddSubjectTagPrefix message filter",
      "type": "object",
      "properties": {
        "enabled": {
          "title": "If true, the list subject prefix is added to post subjects.",
          "type": "boolean"
        }
      },
      "required": [
        "enabled"
      ]
    }
  }
}');
source

pub const MIGRATIONS: &'static [(u32, &'static str, &'static str)] = _

Database migrations.

source

pub fn open_db(conf: Configuration) -> Result<Self>

Creates a new database connection.

Connection supports a limited subset of operations by default (see Connection::untrusted). Use Connection::trusted to remove these limits.

Example
use mailpot::{Connection, Configuration};
use melib::smtp::{SmtpServerConf, SmtpAuth, SmtpSecurity};
let config = Configuration {
    send_mail: mailpot::SendMail::Smtp(
        SmtpServerConf {
            hostname: "127.0.0.1".into(),
            port: 25,
            envelope_from: "foo-chat@example.com".into(),
            auth: SmtpAuth::None,
            security: SmtpSecurity::None,
            extensions: Default::default(),
        }
    ),
    db_path,
    data_path,
    administrators: vec![],
};

let db = Connection::open_or_create_db(config)?;
Examples found in repository?
web/src/main.rs (line 189)
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
async fn root(
    mut session: WritableSession,
    auth: AuthContext,
    State(state): State<Arc<AppState>>,
) -> Result<Html<String>, ResponseError> {
    let db = Connection::open_db(state.conf.clone())?;
    let lists_values = db.lists()?;
    let lists = lists_values
        .iter()
        .map(|list| {
            let months = db.months(list.pk)?;
            let posts = db.list_posts(list.pk, None)?;
            let newest = posts.last().and_then(|p| {
                chrono::Utc
                    .timestamp_opt(p.timestamp as i64, 0)
                    .earliest()
                    .map(|d| d.to_string())
            });
            let list_owners = db.list_owners(list.pk)?;
            let mut list_obj = MailingList::from(list.clone());
            list_obj.set_safety(list_owners.as_slice(), &state.conf.administrators);
            Ok(minijinja::context! {
                newest,
                posts => &posts,
                months => &months,
                list => Value::from_object(list_obj),
            })
        })
        .collect::<Result<Vec<_>, mailpot::Error>>()?;
    let crumbs = vec![Crumb {
        label: "Home".into(),
        url: "/".into(),
    }];

    let context = minijinja::context! {
        page_title => Option::<&'static str>::None,
        lists => &lists,
        current_user => auth.current_user,
        messages => session.drain_messages(),
        crumbs => crumbs,
    };
    Ok(Html(TEMPLATES.get_template("lists.html")?.render(context)?))
}
More examples
Hide additional examples
core/src/connection.rs (line 390)
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
    pub fn open_or_create_db(conf: Configuration) -> Result<Self> {
        if !conf.db_path.exists() {
            let db_path = &conf.db_path;
            use std::os::unix::fs::PermissionsExt;

            info!("Creating database in {}", db_path.display());
            std::fs::File::create(db_path).context("Could not create db path")?;

            let mut child = Command::new(std::env::var("SQLITE_BIN").unwrap_or("sqlite3".into()))
                .arg(db_path)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?;
            let mut stdin = child.stdin.take().unwrap();
            std::thread::spawn(move || {
                stdin
                    .write_all(Self::SCHEMA.as_bytes())
                    .expect("failed to write to stdin");
                if !Self::MIGRATIONS.is_empty() {
                    stdin
                        .write_all(b"\nPRAGMA user_version = ")
                        .expect("failed to write to stdin");
                    stdin
                        .write_all(
                            Self::MIGRATIONS[Self::MIGRATIONS.len() - 1]
                                .0
                                .to_string()
                                .as_bytes(),
                        )
                        .expect("failed to write to stdin");
                    stdin.write_all(b";").expect("failed to write to stdin");
                }
                stdin.flush().expect("could not flush stdin");
            });
            let output = child.wait_with_output()?;
            if !output.status.success() {
                return Err(format!(
                    "Could not initialize sqlite3 database at {}: sqlite3 returned exit code {} \
                     and stderr {} {}",
                    db_path.display(),
                    output.status.code().unwrap_or_default(),
                    String::from_utf8_lossy(&output.stderr),
                    String::from_utf8_lossy(&output.stdout)
                )
                .into());
            }

            let file = std::fs::File::open(db_path)?;
            let metadata = file.metadata()?;
            let mut permissions = metadata.permissions();

            permissions.set_mode(0o600); // Read/write for owner only.
            file.set_permissions(permissions)?;
        }
        Self::open_db(conf)
    }
core/src/postfix.rs (line 282)
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
    pub fn save_maps(&self, config: &Configuration) -> Result<()> {
        let db = Connection::open_db(config.clone())?;
        let Some(postmap) = find_binary_in_path("postmap") else {
            return Err(Error::from(ErrorKind::External(anyhow::Error::msg("Could not find postmap binary in PATH."))));
        };
        let lists = db.lists()?;
        let lists_post_policies = lists
            .into_iter()
            .map(|l| {
                let pk = l.pk;
                Ok((l, db.list_post_policy(pk)?))
            })
            .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
        let content = self.generate_maps(&lists_post_policies);
        let path = self
            .map_output_path
            .as_deref()
            .unwrap_or(&config.data_path)
            .join("mailpot_postfix_map");
        let mut file = BufWriter::new(
            OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&path)
                .context(format!("Could not open {}", path.display()))?,
        );
        file.write_all(content.as_bytes())
            .context(format!("Could not write to {}", path.display()))?;
        file.flush()
            .context(format!("Could not write to {}", path.display()))?;

        let output = std::process::Command::new("sh")
            .arg("-c")
            .arg(&format!("{} {}", postmap.display(), path.display()))
            .output()
            .with_context(|| {
                format!(
                    "Could not execute `postmap` binary in path {}",
                    postmap.display()
                )
            })?;
        if !output.status.success() {
            use std::os::unix::process::ExitStatusExt;
            if let Some(code) = output.status.code() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} exited with {}.\nstderr was:\n---{}---\nstdout was\n---{}---\n",
                        code,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else if let Some(signum) = output.status.signal() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} was killed with signal {}.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        signum,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} failed for unknown reason.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            }
        }

        Ok(())
    }
source

pub fn schema_version(&self) -> Result<u32>

The version of the current schema.

Examples found in repository?
core/src/connection.rs (line 246)
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
    pub fn open_db(conf: Configuration) -> Result<Self> {
        use std::sync::Once;

        use rusqlite::config::DbConfig;

        static INIT_SQLITE_LOGGING: Once = Once::new();

        if !conf.db_path.exists() {
            return Err("Database doesn't exist".into());
        }
        INIT_SQLITE_LOGGING.call_once(|| {
            _ = unsafe { rusqlite::trace::config_log(Some(log_callback)) };
        });
        let conn = DbConnection::open(conf.db_path.to_str().unwrap())?;
        rusqlite::vtab::array::load_module(&conn)?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "foreign_keys", "on")?;
        // synchronise less often to the filesystem
        conn.pragma_update(None, "synchronous", "normal")?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_TRUSTED_SCHEMA, true)?;
        conn.busy_timeout(core::time::Duration::from_millis(500))?;
        conn.busy_handler(Some(|times: i32| -> bool { times < 5 }))?;
        conn.create_scalar_function(
            "validate_json_schema",
            2,
            FunctionFlags::SQLITE_INNOCUOUS
                | FunctionFlags::SQLITE_UTF8
                | FunctionFlags::SQLITE_DETERMINISTIC,
            |ctx| {
                if log::log_enabled!(log::Level::Trace) {
                    rusqlite::trace::log(
                        rusqlite::ffi::SQLITE_NOTICE,
                        "validate_json_schema RUNNING",
                    );
                }
                let map_err = rusqlite::Error::UserFunctionError;
                let schema = ctx.get::<String>(0)?;
                let value = ctx.get::<String>(1)?;
                let schema_val: serde_json::Value = serde_json::from_str(&schema)
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let value: serde_json::Value = serde_json::from_str(&value)
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let compiled = JSONSchema::compile(&schema_val)
                    .map_err(|err| err.to_string())
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let x = if let Err(errors) = compiled.validate(&value) {
                    for err in errors {
                        rusqlite::trace::log(rusqlite::ffi::SQLITE_WARNING, &err.to_string());
                        drop(err);
                    }
                    Ok(false)
                } else {
                    Ok(true)
                };
                x
            },
        )?;

        let ret = Self {
            conf,
            connection: conn,
        };
        if let Some(&(latest, _, _)) = Self::MIGRATIONS.last() {
            let version = ret.schema_version()?;
            trace!(
                "SQLITE user_version PRAGMA returned {version}. Most recent migration is {latest}."
            );
            if version < latest {
                info!("Updating database schema from version {version} to {latest}...");
            }
            ret.migrate(version, latest)?;
        }

        ret.connection.authorizer(Some(user_authorizer_callback));
        Ok(ret)
    }
source

pub fn migrate(&self, from: u32, to: u32) -> Result<()>

Migrate from version from to to.

See Self::MIGRATIONS.

Examples found in repository?
core/src/connection.rs (line 253)
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
    pub fn open_db(conf: Configuration) -> Result<Self> {
        use std::sync::Once;

        use rusqlite::config::DbConfig;

        static INIT_SQLITE_LOGGING: Once = Once::new();

        if !conf.db_path.exists() {
            return Err("Database doesn't exist".into());
        }
        INIT_SQLITE_LOGGING.call_once(|| {
            _ = unsafe { rusqlite::trace::config_log(Some(log_callback)) };
        });
        let conn = DbConnection::open(conf.db_path.to_str().unwrap())?;
        rusqlite::vtab::array::load_module(&conn)?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "foreign_keys", "on")?;
        // synchronise less often to the filesystem
        conn.pragma_update(None, "synchronous", "normal")?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)?;
        conn.set_db_config(DbConfig::SQLITE_DBCONFIG_TRUSTED_SCHEMA, true)?;
        conn.busy_timeout(core::time::Duration::from_millis(500))?;
        conn.busy_handler(Some(|times: i32| -> bool { times < 5 }))?;
        conn.create_scalar_function(
            "validate_json_schema",
            2,
            FunctionFlags::SQLITE_INNOCUOUS
                | FunctionFlags::SQLITE_UTF8
                | FunctionFlags::SQLITE_DETERMINISTIC,
            |ctx| {
                if log::log_enabled!(log::Level::Trace) {
                    rusqlite::trace::log(
                        rusqlite::ffi::SQLITE_NOTICE,
                        "validate_json_schema RUNNING",
                    );
                }
                let map_err = rusqlite::Error::UserFunctionError;
                let schema = ctx.get::<String>(0)?;
                let value = ctx.get::<String>(1)?;
                let schema_val: serde_json::Value = serde_json::from_str(&schema)
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let value: serde_json::Value = serde_json::from_str(&value)
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let compiled = JSONSchema::compile(&schema_val)
                    .map_err(|err| err.to_string())
                    .map_err(Into::into)
                    .map_err(map_err)?;
                let x = if let Err(errors) = compiled.validate(&value) {
                    for err in errors {
                        rusqlite::trace::log(rusqlite::ffi::SQLITE_WARNING, &err.to_string());
                        drop(err);
                    }
                    Ok(false)
                } else {
                    Ok(true)
                };
                x
            },
        )?;

        let ret = Self {
            conf,
            connection: conn,
        };
        if let Some(&(latest, _, _)) = Self::MIGRATIONS.last() {
            let version = ret.schema_version()?;
            trace!(
                "SQLITE user_version PRAGMA returned {version}. Most recent migration is {latest}."
            );
            if version < latest {
                info!("Updating database schema from version {version} to {latest}...");
            }
            ret.migrate(version, latest)?;
        }

        ret.connection.authorizer(Some(user_authorizer_callback));
        Ok(ret)
    }
source

pub fn trusted(self) -> Self

Removes operational limits from this connection. (see Connection::untrusted)

Examples found in repository?
cli/src/main.rs (line 102)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn untrusted(self) -> Self

Sets operational limits for this connection.

  • Allow INSERT, DELETE only for “queue”, “candidate_subscription”, “subscription”.
  • Allow UPDATE only for “subscription” user facing settings.
  • Allow INSERT only for “post”.
  • Allow read access to all tables.
  • Allow SELECT, TRANSACTION, SAVEPOINT, and the strftime function.
  • Deny everything else.
source

pub fn open_or_create_db(conf: Configuration) -> Result<Self>

Create a database if it doesn’t exist and then open it.

Examples found in repository?
cli/src/main.rs (line 102)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn conf(&self) -> &Configuration

Returns a connection’s configuration.

Examples found in repository?
cli/src/main.rs (line 533)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/submission.rs (line 34)
33
34
35
36
37
38
39
40
41
42
    pub fn new_smtp_connection(&self) -> ResultFuture<SmtpConnection> {
        if let crate::SendMail::Smtp(ref smtp_conf) = &self.conf().send_mail {
            let smtp_conf = smtp_conf.clone();
            Ok(Box::pin(async move {
                Ok(SmtpConnection::new_connection(smtp_conf).await?)
            }))
        } else {
            Err("No SMTP configuration found: use the shell command instead.".into())
        }
    }
source

pub fn load_archives(&self) -> Result<()>

Loads archive databases from Configuration::data_path, if any.

source

pub fn lists(&self) -> Result<Vec<DbVal<MailingList>>>

Returns a vector of existing mailing lists.

Examples found in repository?
web/src/main.rs (line 190)
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
async fn root(
    mut session: WritableSession,
    auth: AuthContext,
    State(state): State<Arc<AppState>>,
) -> Result<Html<String>, ResponseError> {
    let db = Connection::open_db(state.conf.clone())?;
    let lists_values = db.lists()?;
    let lists = lists_values
        .iter()
        .map(|list| {
            let months = db.months(list.pk)?;
            let posts = db.list_posts(list.pk, None)?;
            let newest = posts.last().and_then(|p| {
                chrono::Utc
                    .timestamp_opt(p.timestamp as i64, 0)
                    .earliest()
                    .map(|d| d.to_string())
            });
            let list_owners = db.list_owners(list.pk)?;
            let mut list_obj = MailingList::from(list.clone());
            list_obj.set_safety(list_owners.as_slice(), &state.conf.administrators);
            Ok(minijinja::context! {
                newest,
                posts => &posts,
                months => &months,
                list => Value::from_object(list_obj),
            })
        })
        .collect::<Result<Vec<_>, mailpot::Error>>()?;
    let crumbs = vec![Crumb {
        label: "Home".into(),
        url: "/".into(),
    }];

    let context = minijinja::context! {
        page_title => Option::<&'static str>::None,
        lists => &lists,
        current_user => auth.current_user,
        messages => session.drain_messages(),
        crumbs => crumbs,
    };
    Ok(Html(TEMPLATES.get_template("lists.html")?.render(context)?))
}
More examples
Hide additional examples
cli/src/main.rs (line 106)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
core/src/postfix.rs (line 286)
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
    pub fn save_maps(&self, config: &Configuration) -> Result<()> {
        let db = Connection::open_db(config.clone())?;
        let Some(postmap) = find_binary_in_path("postmap") else {
            return Err(Error::from(ErrorKind::External(anyhow::Error::msg("Could not find postmap binary in PATH."))));
        };
        let lists = db.lists()?;
        let lists_post_policies = lists
            .into_iter()
            .map(|l| {
                let pk = l.pk;
                Ok((l, db.list_post_policy(pk)?))
            })
            .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
        let content = self.generate_maps(&lists_post_policies);
        let path = self
            .map_output_path
            .as_deref()
            .unwrap_or(&config.data_path)
            .join("mailpot_postfix_map");
        let mut file = BufWriter::new(
            OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&path)
                .context(format!("Could not open {}", path.display()))?,
        );
        file.write_all(content.as_bytes())
            .context(format!("Could not write to {}", path.display()))?;
        file.flush()
            .context(format!("Could not write to {}", path.display()))?;

        let output = std::process::Command::new("sh")
            .arg("-c")
            .arg(&format!("{} {}", postmap.display(), path.display()))
            .output()
            .with_context(|| {
                format!(
                    "Could not execute `postmap` binary in path {}",
                    postmap.display()
                )
            })?;
        if !output.status.success() {
            use std::os::unix::process::ExitStatusExt;
            if let Some(code) = output.status.code() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} exited with {}.\nstderr was:\n---{}---\nstdout was\n---{}---\n",
                        code,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else if let Some(signum) = output.status.signal() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} was killed with signal {}.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        signum,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} failed for unknown reason.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            }
        }

        Ok(())
    }
core/src/posts.rs (line 131)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source

pub fn list(&self, pk: i64) -> Result<Option<DbVal<MailingList>>>

Fetch a mailing list by primary key.

Examples found in repository?
cli/src/main.rs (line 838)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/connection.rs (line 686)
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    pub fn update_list(&self, change_set: MailingListChangeset) -> Result<()> {
        if matches!(
            change_set,
            MailingListChangeset {
                pk: _,
                name: None,
                id: None,
                address: None,
                description: None,
                archive_url: None,
                owner_local_part: None,
                request_local_part: None,
                verify: None,
                hidden: None,
                enabled: None,
            }
        ) {
            return self.list(change_set.pk).map(|_| ());
        }

        let MailingListChangeset {
            pk,
            name,
            id,
            address,
            description,
            archive_url,
            owner_local_part,
            request_local_part,
            verify,
            hidden,
            enabled,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_list)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!("UPDATE list SET ", stringify!($field), " = ? WHERE pk = ?;"),
                        rusqlite::params![&$field, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(id);
        update!(address);
        update!(description);
        update!(archive_url);
        update!(owner_local_part);
        update!(request_local_part);
        update!(verify);
        update!(hidden);
        update!(enabled);

        tx.commit()?;
        Ok(())
    }
source

pub fn list_by_id<S: AsRef<str>>( &self, id: S ) -> Result<Option<DbVal<MailingList>>>

Fetch a mailing list by id.

source

pub fn create_list(&self, new_val: MailingList) -> Result<DbVal<MailingList>>

Create a new list.

Examples found in repository?
cli/src/main.rs (lines 494-502)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn list_posts( &self, list_pk: i64, _date_range: Option<(String, String)> ) -> Result<Vec<DbVal<Post>>>

Fetch all posts of a mailing list.

Examples found in repository?
web/src/main.rs (line 195)
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
async fn root(
    mut session: WritableSession,
    auth: AuthContext,
    State(state): State<Arc<AppState>>,
) -> Result<Html<String>, ResponseError> {
    let db = Connection::open_db(state.conf.clone())?;
    let lists_values = db.lists()?;
    let lists = lists_values
        .iter()
        .map(|list| {
            let months = db.months(list.pk)?;
            let posts = db.list_posts(list.pk, None)?;
            let newest = posts.last().and_then(|p| {
                chrono::Utc
                    .timestamp_opt(p.timestamp as i64, 0)
                    .earliest()
                    .map(|d| d.to_string())
            });
            let list_owners = db.list_owners(list.pk)?;
            let mut list_obj = MailingList::from(list.clone());
            list_obj.set_safety(list_owners.as_slice(), &state.conf.administrators);
            Ok(minijinja::context! {
                newest,
                posts => &posts,
                months => &months,
                list => Value::from_object(list_obj),
            })
        })
        .collect::<Result<Vec<_>, mailpot::Error>>()?;
    let crumbs = vec![Crumb {
        label: "Home".into(),
        url: "/".into(),
    }];

    let context = minijinja::context! {
        page_title => Option::<&'static str>::None,
        lists => &lists,
        current_user => auth.current_user,
        messages => session.drain_messages(),
        crumbs => crumbs,
    };
    Ok(Html(TEMPLATES.get_template("lists.html")?.render(context)?))
}
source

pub fn list_owners(&self, pk: i64) -> Result<Vec<DbVal<ListOwner>>>

Fetch the owners of a mailing list.

Examples found in repository?
web/src/main.rs (line 202)
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
async fn root(
    mut session: WritableSession,
    auth: AuthContext,
    State(state): State<Arc<AppState>>,
) -> Result<Html<String>, ResponseError> {
    let db = Connection::open_db(state.conf.clone())?;
    let lists_values = db.lists()?;
    let lists = lists_values
        .iter()
        .map(|list| {
            let months = db.months(list.pk)?;
            let posts = db.list_posts(list.pk, None)?;
            let newest = posts.last().and_then(|p| {
                chrono::Utc
                    .timestamp_opt(p.timestamp as i64, 0)
                    .earliest()
                    .map(|d| d.to_string())
            });
            let list_owners = db.list_owners(list.pk)?;
            let mut list_obj = MailingList::from(list.clone());
            list_obj.set_safety(list_owners.as_slice(), &state.conf.administrators);
            Ok(minijinja::context! {
                newest,
                posts => &posts,
                months => &months,
                list => Value::from_object(list_obj),
            })
        })
        .collect::<Result<Vec<_>, mailpot::Error>>()?;
    let crumbs = vec![Crumb {
        label: "Home".into(),
        url: "/".into(),
    }];

    let context = minijinja::context! {
        page_title => Option::<&'static str>::None,
        lists => &lists,
        current_user => auth.current_user,
        messages => session.drain_messages(),
        crumbs => crumbs,
    };
    Ok(Html(TEMPLATES.get_template("lists.html")?.render(context)?))
}
More examples
Hide additional examples
cli/src/main.rs (line 120)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
core/src/posts.rs (line 178)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn remove_list_owner(&self, list_pk: i64, owner_pk: i64) -> Result<()>

Remove an owner of a mailing list.

Examples found in repository?
cli/src/main.rs (line 364)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn add_list_owner(&self, list_owner: ListOwner) -> Result<DbVal<ListOwner>>

Add an owner of a mailing list.

Examples found in repository?
cli/src/main.rs (line 360)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn update_list(&self, change_set: MailingListChangeset) -> Result<()>

Update a mailing list.

Examples found in repository?
cli/src/main.rs (line 428)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn transaction( &mut self, behavior: TransactionBehavior ) -> Result<Transaction<'_>>

Execute operations inside an SQL transaction.

Examples found in repository?
cli/src/main.rs (line 472)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn savepoint(&self, name: Option<&'static str>) -> Result<Savepoint<'_>>

Execute operations inside an SQL savepoint.

Examples found in repository?
core/src/connection.rs (line 280)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    pub fn migrate(&self, mut from: u32, to: u32) -> Result<()> {
        if from == to {
            return Ok(());
        }

        let undo = from > to;
        let tx = self.savepoint(Some(stringify!(migrate)))?;

        while from != to {
            log::trace!(
                "exec migration from {from} to {to}, type: {}do",
                if undo { "un " } else { "re" }
            );
            if undo {
                trace!("{}", Self::MIGRATIONS[from as usize - 1].2);
                tx.connection
                    .execute_batch(Self::MIGRATIONS[from as usize - 1].2)?;
                from -= 1;
            } else {
                trace!("{}", Self::MIGRATIONS[from as usize].1);
                tx.connection
                    .execute_batch(Self::MIGRATIONS[from as usize].1)?;
                from += 1;
            }
        }
        tx.connection
            .pragma_update(None, "user_version", Self::MIGRATIONS[to as usize - 1].0)?;

        tx.commit()?;

        Ok(())
    }

    /// Removes operational limits from this connection. (see
    /// [`Connection::untrusted`])
    #[must_use]
    pub fn trusted(self) -> Self {
        self.connection
            .authorizer::<fn(rusqlite::hooks::AuthContext<'_>) -> rusqlite::hooks::Authorization>(
                None,
            );
        self
    }

    // [tag:sync_auth_doc]
    /// Sets operational limits for this connection.
    ///
    /// - Allow `INSERT`, `DELETE` only for "queue", "candidate_subscription",
    ///   "subscription".
    /// - Allow `UPDATE` only for "subscription" user facing settings.
    /// - Allow `INSERT` only for "post".
    /// - Allow read access to all tables.
    /// - Allow `SELECT`, `TRANSACTION`, `SAVEPOINT`, and the `strftime`
    ///   function.
    /// - Deny everything else.
    pub fn untrusted(self) -> Self {
        self.connection.authorizer(Some(user_authorizer_callback));
        self
    }

    /// Create a database if it doesn't exist and then open it.
    pub fn open_or_create_db(conf: Configuration) -> Result<Self> {
        if !conf.db_path.exists() {
            let db_path = &conf.db_path;
            use std::os::unix::fs::PermissionsExt;

            info!("Creating database in {}", db_path.display());
            std::fs::File::create(db_path).context("Could not create db path")?;

            let mut child = Command::new(std::env::var("SQLITE_BIN").unwrap_or("sqlite3".into()))
                .arg(db_path)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()?;
            let mut stdin = child.stdin.take().unwrap();
            std::thread::spawn(move || {
                stdin
                    .write_all(Self::SCHEMA.as_bytes())
                    .expect("failed to write to stdin");
                if !Self::MIGRATIONS.is_empty() {
                    stdin
                        .write_all(b"\nPRAGMA user_version = ")
                        .expect("failed to write to stdin");
                    stdin
                        .write_all(
                            Self::MIGRATIONS[Self::MIGRATIONS.len() - 1]
                                .0
                                .to_string()
                                .as_bytes(),
                        )
                        .expect("failed to write to stdin");
                    stdin.write_all(b";").expect("failed to write to stdin");
                }
                stdin.flush().expect("could not flush stdin");
            });
            let output = child.wait_with_output()?;
            if !output.status.success() {
                return Err(format!(
                    "Could not initialize sqlite3 database at {}: sqlite3 returned exit code {} \
                     and stderr {} {}",
                    db_path.display(),
                    output.status.code().unwrap_or_default(),
                    String::from_utf8_lossy(&output.stderr),
                    String::from_utf8_lossy(&output.stdout)
                )
                .into());
            }

            let file = std::fs::File::open(db_path)?;
            let metadata = file.metadata()?;
            let mut permissions = metadata.permissions();

            permissions.set_mode(0o600); // Read/write for owner only.
            file.set_permissions(permissions)?;
        }
        Self::open_db(conf)
    }

    /// Returns a connection's configuration.
    pub fn conf(&self) -> &Configuration {
        &self.conf
    }

    /// Loads archive databases from [`Configuration::data_path`], if any.
    pub fn load_archives(&self) -> Result<()> {
        let tx = self.savepoint(Some(stringify!(load_archives)))?;
        {
            let mut stmt = tx.connection.prepare("ATTACH ? AS ?;")?;
            for archive in std::fs::read_dir(&self.conf.data_path)? {
                let archive = archive?;
                let path = archive.path();
                let name = path.file_name().unwrap_or_default();
                if path == self.conf.db_path {
                    continue;
                }
                stmt.execute(rusqlite::params![
                    path.to_str().unwrap(),
                    name.to_str().unwrap()
                ])?;
            }
        }
        tx.commit()?;

        Ok(())
    }

    /// Returns a vector of existing mailing lists.
    pub fn lists(&self) -> Result<Vec<DbVal<MailingList>>> {
        let mut stmt = self.connection.prepare("SELECT * FROM list;")?;
        let list_iter = stmt.query_map([], |row| {
            let pk = row.get("pk")?;
            let topics: serde_json::Value = row.get("topics")?;
            let topics = MailingList::topics_from_json_value(topics)?;
            Ok(DbVal(
                MailingList {
                    pk,
                    name: row.get("name")?,
                    id: row.get("id")?,
                    address: row.get("address")?,
                    description: row.get("description")?,
                    topics,
                    archive_url: row.get("archive_url")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Fetch a mailing list by primary key.
    pub fn list(&self, pk: i64) -> Result<Option<DbVal<MailingList>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM list WHERE pk = ?;")?;
        let ret = stmt
            .query_row([&pk], |row| {
                let pk = row.get("pk")?;
                let topics: serde_json::Value = row.get("topics")?;
                let topics = MailingList::topics_from_json_value(topics)?;
                Ok(DbVal(
                    MailingList {
                        pk,
                        name: row.get("name")?,
                        id: row.get("id")?,
                        address: row.get("address")?,
                        description: row.get("description")?,
                        topics,
                        archive_url: row.get("archive_url")?,
                    },
                    pk,
                ))
            })
            .optional()?;
        Ok(ret)
    }

    /// Fetch a mailing list by id.
    pub fn list_by_id<S: AsRef<str>>(&self, id: S) -> Result<Option<DbVal<MailingList>>> {
        let id = id.as_ref();
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM list WHERE id = ?;")?;
        let ret = stmt
            .query_row([&id], |row| {
                let pk = row.get("pk")?;
                let topics: serde_json::Value = row.get("topics")?;
                let topics = MailingList::topics_from_json_value(topics)?;
                Ok(DbVal(
                    MailingList {
                        pk,
                        name: row.get("name")?,
                        id: row.get("id")?,
                        address: row.get("address")?,
                        description: row.get("description")?,
                        topics,
                        archive_url: row.get("archive_url")?,
                    },
                    pk,
                ))
            })
            .optional()?;

        Ok(ret)
    }

    /// Create a new list.
    pub fn create_list(&self, new_val: MailingList) -> Result<DbVal<MailingList>> {
        let mut stmt = self.connection.prepare(
            "INSERT INTO list(name, id, address, description, archive_url, topics) VALUES(?, ?, \
             ?, ?, ?, ?) RETURNING *;",
        )?;
        let ret = stmt.query_row(
            rusqlite::params![
                &new_val.name,
                &new_val.id,
                &new_val.address,
                new_val.description.as_ref(),
                new_val.archive_url.as_ref(),
                serde_json::json!(new_val.topics.as_slice()),
            ],
            |row| {
                let pk = row.get("pk")?;
                let topics: serde_json::Value = row.get("topics")?;
                let topics = MailingList::topics_from_json_value(topics)?;
                Ok(DbVal(
                    MailingList {
                        pk,
                        name: row.get("name")?,
                        id: row.get("id")?,
                        address: row.get("address")?,
                        description: row.get("description")?,
                        topics,
                        archive_url: row.get("archive_url")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("create_list {:?}.", &ret);
        Ok(ret)
    }

    /// Fetch all posts of a mailing list.
    pub fn list_posts(
        &self,
        list_pk: i64,
        _date_range: Option<(String, String)>,
    ) -> Result<Vec<DbVal<Post>>> {
        let mut stmt = self.connection.prepare(
            "SELECT *, strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') AS month_year \
             FROM post WHERE list = ? ORDER BY timestamp ASC;",
        )?;
        let iter = stmt.query_map(rusqlite::params![&list_pk], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                Post {
                    pk,
                    list: row.get("list")?,
                    envelope_from: row.get("envelope_from")?,
                    address: row.get("address")?,
                    message_id: row.get("message_id")?,
                    message: row.get("message")?,
                    timestamp: row.get("timestamp")?,
                    datetime: row.get("datetime")?,
                    month_year: row.get("month_year")?,
                },
                pk,
            ))
        })?;
        let mut ret = vec![];
        for post in iter {
            let post = post?;
            ret.push(post);
        }

        trace!("list_posts {:?}.", &ret);
        Ok(ret)
    }

    /// Fetch the owners of a mailing list.
    pub fn list_owners(&self, pk: i64) -> Result<Vec<DbVal<ListOwner>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM owner WHERE list = ?;")?;
        let list_iter = stmt.query_map([&pk], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                ListOwner {
                    pk,
                    list: row.get("list")?,
                    address: row.get("address")?,
                    name: row.get("name")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Remove an owner of a mailing list.
    pub fn remove_list_owner(&self, list_pk: i64, owner_pk: i64) -> Result<()> {
        self.connection
            .query_row(
                "DELETE FROM owner WHERE list = ? AND pk = ? RETURNING *;",
                rusqlite::params![&list_pk, &owner_pk],
                |_| Ok(()),
            )
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err).chain_err(|| NotFound("list or list owner not found!"))
                } else {
                    err.into()
                }
            })?;
        Ok(())
    }

    /// Add an owner of a mailing list.
    pub fn add_list_owner(&self, list_owner: ListOwner) -> Result<DbVal<ListOwner>> {
        let mut stmt = self.connection.prepare(
            "INSERT OR REPLACE INTO owner(list, address, name) VALUES (?, ?, ?) RETURNING *;",
        )?;
        let list_pk = list_owner.list;
        let ret = stmt
            .query_row(
                rusqlite::params![&list_pk, &list_owner.address, &list_owner.name,],
                |row| {
                    let pk = row.get("pk")?;
                    Ok(DbVal(
                        ListOwner {
                            pk,
                            list: row.get("list")?,
                            address: row.get("address")?,
                            name: row.get("name")?,
                        },
                        pk,
                    ))
                },
            )
            .map_err(|err| {
                if matches!(
                    err,
                    rusqlite::Error::SqliteFailure(
                        rusqlite::ffi::Error {
                            code: rusqlite::ffi::ErrorCode::ConstraintViolation,
                            extended_code: 787
                        },
                        _
                    )
                ) {
                    Error::from(err).chain_err(|| NotFound("Could not find a list with this pk."))
                } else {
                    err.into()
                }
            })?;

        trace!("add_list_owner {:?}.", &ret);
        Ok(ret)
    }

    /// Update a mailing list.
    pub fn update_list(&self, change_set: MailingListChangeset) -> Result<()> {
        if matches!(
            change_set,
            MailingListChangeset {
                pk: _,
                name: None,
                id: None,
                address: None,
                description: None,
                archive_url: None,
                owner_local_part: None,
                request_local_part: None,
                verify: None,
                hidden: None,
                enabled: None,
            }
        ) {
            return self.list(change_set.pk).map(|_| ());
        }

        let MailingListChangeset {
            pk,
            name,
            id,
            address,
            description,
            archive_url,
            owner_local_part,
            request_local_part,
            verify,
            hidden,
            enabled,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_list)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!("UPDATE list SET ", stringify!($field), " = ? WHERE pk = ?;"),
                        rusqlite::params![&$field, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(id);
        update!(address);
        update!(description);
        update!(archive_url);
        update!(owner_local_part);
        update!(request_local_part);
        update!(verify);
        update!(hidden);
        update!(enabled);

        tx.commit()?;
        Ok(())
    }
More examples
Hide additional examples
core/src/queue.rs (line 240)
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
    pub fn delete_from_queue(&self, queue: Queue, index: Vec<i64>) -> Result<Vec<QueueEntry>> {
        let tx = self.savepoint(Some(stringify!(delete_from_queue)))?;

        let cl = |row: &rusqlite::Row<'_>| {
            Ok(QueueEntry {
                pk: -1,
                queue,
                list: row.get::<_, Option<i64>>("list")?,
                comment: row.get::<_, Option<String>>("comment")?,
                to_addresses: row.get::<_, String>("to_addresses")?,
                from_address: row.get::<_, String>("from_address")?,
                subject: row.get::<_, String>("subject")?,
                message_id: row.get::<_, String>("message_id")?,
                message: row.get::<_, Vec<u8>>("message")?,
                timestamp: row.get::<_, u64>("timestamp")?,
                datetime: row.get::<_, DateTime>("datetime")?,
            })
        };
        let mut stmt = if index.is_empty() {
            tx.connection
                .prepare("DELETE FROM queue WHERE which = ? RETURNING *;")?
        } else {
            tx.connection
                .prepare("DELETE FROM queue WHERE which = ? AND pk IN rarray(?) RETURNING *;")?
        };
        let iter = if index.is_empty() {
            stmt.query_map([&queue.as_str()], cl)?
        } else {
            // Note: A `Rc<Vec<Value>>` must be used as the parameter.
            let index = std::rc::Rc::new(
                index
                    .into_iter()
                    .map(rusqlite::types::Value::from)
                    .collect::<Vec<rusqlite::types::Value>>(),
            );
            stmt.query_map(rusqlite::params![queue.as_str(), index], cl)?
        };

        let mut ret = vec![];
        for item in iter {
            let item = item?;
            ret.push(item);
        }
        drop(stmt);
        tx.commit()?;
        Ok(ret)
    }
core/src/subscriptions.rs (line 350)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    pub fn update_subscription(&self, change_set: ListSubscriptionChangeset) -> Result<()> {
        let pk = self
            .list_subscription_by_address(change_set.list, &change_set.address)?
            .pk;
        if matches!(
            change_set,
            ListSubscriptionChangeset {
                list: _,
                address: _,
                account: None,
                name: None,
                digest: None,
                verified: None,
                hide_address: None,
                receive_duplicates: None,
                receive_own_posts: None,
                receive_confirmation: None,
                enabled: None,
            }
        ) {
            return Ok(());
        }

        let ListSubscriptionChangeset {
            list,
            address: _,
            name,
            account,
            digest,
            enabled,
            verified,
            hide_address,
            receive_duplicates,
            receive_own_posts,
            receive_confirmation,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_subscription)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!(
                            "UPDATE subscription SET ",
                            stringify!($field),
                            " = ? WHERE list = ? AND pk = ?;"
                        ),
                        rusqlite::params![&$field, &list, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(account);
        update!(digest);
        update!(enabled);
        update!(verified);
        update!(hide_address);
        update!(receive_duplicates);
        update!(receive_own_posts);
        update!(receive_confirmation);

        tx.commit()?;
        Ok(())
    }

    /// Fetch account by pk.
    pub fn account(&self, pk: i64) -> Result<Option<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account WHERE pk = ?;")?;

        let ret = stmt
            .query_row(rusqlite::params![&pk], |row| {
                let _pk: i64 = row.get("pk")?;
                debug_assert_eq!(pk, _pk);
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            })
            .optional()?;
        Ok(ret)
    }

    /// Fetch account by address.
    pub fn account_by_address(&self, address: &str) -> Result<Option<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account WHERE address = ?;")?;

        let ret = stmt
            .query_row(rusqlite::params![&address], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            })
            .optional()?;
        Ok(ret)
    }

    /// Fetch all subscriptions of an account by primary key.
    pub fn account_subscriptions(&self, pk: i64) -> Result<Vec<DbVal<ListSubscription>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM subscription WHERE account = ?;")?;
        let list_iter = stmt.query_map([&pk], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                ListSubscription {
                    pk: row.get("pk")?,
                    list: row.get("list")?,
                    address: row.get("address")?,
                    account: row.get("account")?,
                    name: row.get("name")?,
                    digest: row.get("digest")?,
                    enabled: row.get("enabled")?,
                    verified: row.get("verified")?,
                    hide_address: row.get("hide_address")?,
                    receive_duplicates: row.get("receive_duplicates")?,
                    receive_own_posts: row.get("receive_own_posts")?,
                    receive_confirmation: row.get("receive_confirmation")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Fetch all accounts.
    pub fn accounts(&self) -> Result<Vec<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account ORDER BY pk ASC;")?;
        let list_iter = stmt.query_map([], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                Account {
                    pk,
                    name: row.get("name")?,
                    address: row.get("address")?,
                    public_key: row.get("public_key")?,
                    password: row.get("password")?,
                    enabled: row.get("enabled")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Add account.
    pub fn add_account(&self, new_val: Account) -> Result<DbVal<Account>> {
        let mut stmt = self
            .connection
            .prepare(
                "INSERT INTO account(name, address, public_key, password, enabled) VALUES(?, ?, \
                 ?, ?, ?) RETURNING *;",
            )
            .unwrap();
        let ret = stmt.query_row(
            rusqlite::params![
                &new_val.name,
                &new_val.address,
                &new_val.public_key,
                &new_val.password,
                &new_val.enabled,
            ],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("add_account {:?}.", &ret);
        Ok(ret)
    }

    /// Remove an account by their address.
    pub fn remove_account(&self, address: &str) -> Result<()> {
        self.connection
            .query_row(
                "DELETE FROM account WHERE address = ? RETURNING *;",
                rusqlite::params![&address],
                |_| Ok(()),
            )
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err).chain_err(|| NotFound("account not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(())
    }

    /// Update an account.
    pub fn update_account(&self, change_set: AccountChangeset) -> Result<()> {
        let Some(acc) = self.account_by_address(&change_set.address)? else {
            return Err(NotFound("account with this address not found!").into());
        };
        let pk = acc.pk;
        if matches!(
            change_set,
            AccountChangeset {
                address: _,
                name: None,
                public_key: None,
                password: None,
                enabled: None,
            }
        ) {
            return Ok(());
        }

        let AccountChangeset {
            address: _,
            name,
            public_key,
            password,
            enabled,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_account)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!(
                            "UPDATE account SET ",
                            stringify!($field),
                            " = ? WHERE pk = ?;"
                        ),
                        rusqlite::params![&$field, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(public_key);
        update!(password);
        update!(enabled);

        tx.commit()?;
        Ok(())
    }
source§

impl Connection

source

pub fn get_settings( &self, list_pk: i64 ) -> Result<HashMap<String, DbVal<Value>>>

Get json settings.

Examples found in repository?
core/src/posts.rs (line 186)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source§

impl Connection

source

pub fn list_filters( &self, _list: &DbVal<MailingList> ) -> Vec<Box<dyn PostFilter>>

Return the post filters of a mailing list.

Examples found in repository?
core/src/posts.rs (line 176)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source§

impl Connection

source

pub fn list_post_policy(&self, pk: i64) -> Result<Option<DbVal<PostPolicy>>>

Fetch the post policy of a mailing list.

Examples found in repository?
cli/src/main.rs (line 129)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/postfix.rs (line 291)
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
    pub fn save_maps(&self, config: &Configuration) -> Result<()> {
        let db = Connection::open_db(config.clone())?;
        let Some(postmap) = find_binary_in_path("postmap") else {
            return Err(Error::from(ErrorKind::External(anyhow::Error::msg("Could not find postmap binary in PATH."))));
        };
        let lists = db.lists()?;
        let lists_post_policies = lists
            .into_iter()
            .map(|l| {
                let pk = l.pk;
                Ok((l, db.list_post_policy(pk)?))
            })
            .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
        let content = self.generate_maps(&lists_post_policies);
        let path = self
            .map_output_path
            .as_deref()
            .unwrap_or(&config.data_path)
            .join("mailpot_postfix_map");
        let mut file = BufWriter::new(
            OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&path)
                .context(format!("Could not open {}", path.display()))?,
        );
        file.write_all(content.as_bytes())
            .context(format!("Could not write to {}", path.display()))?;
        file.flush()
            .context(format!("Could not write to {}", path.display()))?;

        let output = std::process::Command::new("sh")
            .arg("-c")
            .arg(&format!("{} {}", postmap.display(), path.display()))
            .output()
            .with_context(|| {
                format!(
                    "Could not execute `postmap` binary in path {}",
                    postmap.display()
                )
            })?;
        if !output.status.success() {
            use std::os::unix::process::ExitStatusExt;
            if let Some(code) = output.status.code() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} exited with {}.\nstderr was:\n---{}---\nstdout was\n---{}---\n",
                        code,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else if let Some(signum) = output.status.signal() {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} was killed with signal {}.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        signum,
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            } else {
                return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
                    format!(
                        "{} failed for unknown reason.\nstderr was:\n---{}---\nstdout \
                         was\n---{}---\n",
                        postmap.display(),
                        String::from_utf8_lossy(&output.stderr),
                        String::from_utf8_lossy(&output.stdout)
                    ),
                ))));
            }
        }

        Ok(())
    }
core/src/posts.rs (line 181)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }

    /// Fetch all year and month values for which at least one post exists in
    /// `yyyy-mm` format.
    pub fn months(&self, list_pk: i64) -> Result<Vec<String>> {
        let mut stmt = self.connection.prepare(
            "SELECT DISTINCT strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') FROM post \
             WHERE list = ?;",
        )?;
        let months_iter = stmt.query_map([list_pk], |row| {
            let val: String = row.get(0)?;
            Ok(val)
        })?;

        let mut ret = vec![];
        for month in months_iter {
            let month = month?;
            ret.push(month);
        }
        Ok(ret)
    }

    /// Find a post by its `Message-ID` email header.
    pub fn list_post_by_message_id(
        &self,
        list_pk: i64,
        message_id: &str,
    ) -> Result<Option<DbVal<Post>>> {
        let mut stmt = self.connection.prepare(
            "SELECT *, strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') AS month_year \
             FROM post WHERE list = ? AND message_id = ?;",
        )?;
        let ret = stmt
            .query_row(rusqlite::params![&list_pk, &message_id], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Post {
                        pk,
                        list: row.get("list")?,
                        envelope_from: row.get("envelope_from")?,
                        address: row.get("address")?,
                        message_id: row.get("message_id")?,
                        message: row.get("message")?,
                        timestamp: row.get("timestamp")?,
                        datetime: row.get("datetime")?,
                        month_year: row.get("month_year")?,
                    },
                    pk,
                ))
            })
            .optional()?;

        Ok(ret)
    }

    /// Helper function to send a template reply.
    pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
        &self,
        render_context: TemplateRenderContext<'ctx, F>,
        recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
    ) -> Result<()> {
        let TemplateRenderContext {
            template,
            default_fn,
            list,
            context,
            queue,
            comment,
        } = render_context;

        let post_policy = self.list_post_policy(list.pk)?;
        let subscription_policy = self.list_subscription_policy(list.pk)?;

        let templ = self
            .fetch_template(template, Some(list.pk))?
            .map(DbVal::into_inner)
            .or_else(|| default_fn.map(|f| f()))
            .ok_or_else(|| -> crate::Error {
                format!("Template with name {template:?} was not found.").into()
            })?;

        let mut draft = templ.render(context)?;
        draft.headers.insert(
            melib::HeaderName::new_unchecked("From"),
            list.request_subaddr(),
        );
        for addr in recipients {
            let mut draft = draft.clone();
            draft
                .headers
                .insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
            list.insert_headers(
                &mut draft,
                post_policy.as_deref(),
                subscription_policy.as_deref(),
            );
            self.insert_to_queue(QueueEntry::new(
                queue,
                Some(list.pk),
                None,
                draft.finalise()?.as_bytes(),
                Some(comment.to_string()),
            )?)?;
        }
        Ok(())
    }
source

pub fn remove_list_post_policy( &self, list_pk: i64, policy_pk: i64 ) -> Result<()>

Remove an existing list policy.

Examples
let db = Connection::open_or_create_db(config).unwrap().trusted();
let list = db
    .create_list(MailingList {
        pk: 0,
        name: "foobar chat".into(),
        id: "foo-chat".into(),
        address: "foo-chat@example.com".into(),
        description: None,
        topics: vec![],
        archive_url: None,
    })
    .unwrap();

let pol = db
    .set_list_post_policy(PostPolicy {
        pk: -1,
        list: list.pk(),
        announce_only: false,
        subscription_only: true,
        approval_needed: false,
        open: false,
        custom: false,
    })
    .unwrap();
db.remove_list_post_policy(list.pk(), pol.pk()).unwrap();
let db = Connection::open_or_create_db(config).unwrap().trusted();
db.remove_list_post_policy(1, 1).unwrap();
Examples found in repository?
cli/src/main.rs (line 327)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn set_list_post_policy( &self, policy: PostPolicy ) -> Result<DbVal<PostPolicy>>

Set the unique post policy for a list.

Examples found in repository?
cli/src/main.rs (line 323)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source§

impl Connection

source

pub fn list_subscription_policy( &self, pk: i64 ) -> Result<Option<DbVal<SubscriptionPolicy>>>

Fetch the subscription policy of a mailing list.

Examples found in repository?
cli/src/main.rs (line 134)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 182)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }

    /// Fetch all year and month values for which at least one post exists in
    /// `yyyy-mm` format.
    pub fn months(&self, list_pk: i64) -> Result<Vec<String>> {
        let mut stmt = self.connection.prepare(
            "SELECT DISTINCT strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') FROM post \
             WHERE list = ?;",
        )?;
        let months_iter = stmt.query_map([list_pk], |row| {
            let val: String = row.get(0)?;
            Ok(val)
        })?;

        let mut ret = vec![];
        for month in months_iter {
            let month = month?;
            ret.push(month);
        }
        Ok(ret)
    }

    /// Find a post by its `Message-ID` email header.
    pub fn list_post_by_message_id(
        &self,
        list_pk: i64,
        message_id: &str,
    ) -> Result<Option<DbVal<Post>>> {
        let mut stmt = self.connection.prepare(
            "SELECT *, strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') AS month_year \
             FROM post WHERE list = ? AND message_id = ?;",
        )?;
        let ret = stmt
            .query_row(rusqlite::params![&list_pk, &message_id], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Post {
                        pk,
                        list: row.get("list")?,
                        envelope_from: row.get("envelope_from")?,
                        address: row.get("address")?,
                        message_id: row.get("message_id")?,
                        message: row.get("message")?,
                        timestamp: row.get("timestamp")?,
                        datetime: row.get("datetime")?,
                        month_year: row.get("month_year")?,
                    },
                    pk,
                ))
            })
            .optional()?;

        Ok(ret)
    }

    /// Helper function to send a template reply.
    pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
        &self,
        render_context: TemplateRenderContext<'ctx, F>,
        recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
    ) -> Result<()> {
        let TemplateRenderContext {
            template,
            default_fn,
            list,
            context,
            queue,
            comment,
        } = render_context;

        let post_policy = self.list_post_policy(list.pk)?;
        let subscription_policy = self.list_subscription_policy(list.pk)?;

        let templ = self
            .fetch_template(template, Some(list.pk))?
            .map(DbVal::into_inner)
            .or_else(|| default_fn.map(|f| f()))
            .ok_or_else(|| -> crate::Error {
                format!("Template with name {template:?} was not found.").into()
            })?;

        let mut draft = templ.render(context)?;
        draft.headers.insert(
            melib::HeaderName::new_unchecked("From"),
            list.request_subaddr(),
        );
        for addr in recipients {
            let mut draft = draft.clone();
            draft
                .headers
                .insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
            list.insert_headers(
                &mut draft,
                post_policy.as_deref(),
                subscription_policy.as_deref(),
            );
            self.insert_to_queue(QueueEntry::new(
                queue,
                Some(list.pk),
                None,
                draft.finalise()?.as_bytes(),
                Some(comment.to_string()),
            )?)?;
        }
        Ok(())
    }
source

pub fn remove_list_subscription_policy( &self, list_pk: i64, policy_pk: i64 ) -> Result<()>

Remove an existing subscription policy.

Examples
let db = Connection::open_or_create_db(config).unwrap().trusted();
let list = db
    .create_list(MailingList {
        pk: 0,
        name: "foobar chat".into(),
        id: "foo-chat".into(),
        address: "foo-chat@example.com".into(),
        description: None,
        topics: vec![],
        archive_url: None,
    })
    .unwrap();
let pol = db
    .set_list_subscription_policy(SubscriptionPolicy {
        pk: -1,
        list: list.pk(),
        send_confirmation: false,
        open: true,
        manual: false,
        request: false,
        custom: false,
    })
    .unwrap();
db.remove_list_subscription_policy(list.pk(), pol.pk())
    .unwrap();
let db = Connection::open_or_create_db(config).unwrap().trusted();
db.remove_list_post_policy(1, 1).unwrap();
Examples found in repository?
cli/src/main.rs (line 350)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn set_list_subscription_policy( &self, policy: SubscriptionPolicy ) -> Result<DbVal<SubscriptionPolicy>>

Set the unique post policy for a list.

Examples found in repository?
cli/src/main.rs (line 346)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source§

impl Connection

source

pub fn insert_post( &self, list_pk: i64, message: &[u8], env: &Envelope ) -> Result<i64>

Insert a mailing list post into the database.

Examples found in repository?
cli/src/main.rs (line 759)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 208)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source

pub fn post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()>

Process a new mailing list post.

In case multiple processes can access the database at any time, use an EXCLUSIVE transaction before calling this function. See Connection::transaction.

Examples found in repository?
cli/src/main.rs (line 525)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()>

Examples found in repository?
core/src/posts.rs (line 92)
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
    pub fn post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        let result = self.inner_post(env, raw, _dry_run);
        if let Err(err) = result {
            return match self.insert_to_queue(QueueEntry::new(
                Queue::Error,
                None,
                Some(Cow::Borrowed(env)),
                raw,
                Some(err.to_string()),
            )?) {
                Ok(idx) => {
                    log::info!(
                        "Inserted mail from {:?} into error_queue at index {}",
                        env.from(),
                        idx
                    );
                    Err(err)
                }
                Err(err2) => {
                    log::error!(
                        "Could not insert mail from {:?} into error_queue: {err2}",
                        env.from(),
                    );

                    Err(err.chain_err(|| err2))
                }
            };
        }
        result
    }
source

pub fn request( &self, list: &DbVal<MailingList>, request: ListRequest, env: &Envelope, raw: &[u8] ) -> Result<()>

Process a new mailing list request.

Examples found in repository?
core/src/posts.rs (line 143)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source

pub fn months(&self, list_pk: i64) -> Result<Vec<String>>

Fetch all year and month values for which at least one post exists in yyyy-mm format.

Examples found in repository?
web/src/main.rs (line 194)
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
async fn root(
    mut session: WritableSession,
    auth: AuthContext,
    State(state): State<Arc<AppState>>,
) -> Result<Html<String>, ResponseError> {
    let db = Connection::open_db(state.conf.clone())?;
    let lists_values = db.lists()?;
    let lists = lists_values
        .iter()
        .map(|list| {
            let months = db.months(list.pk)?;
            let posts = db.list_posts(list.pk, None)?;
            let newest = posts.last().and_then(|p| {
                chrono::Utc
                    .timestamp_opt(p.timestamp as i64, 0)
                    .earliest()
                    .map(|d| d.to_string())
            });
            let list_owners = db.list_owners(list.pk)?;
            let mut list_obj = MailingList::from(list.clone());
            list_obj.set_safety(list_owners.as_slice(), &state.conf.administrators);
            Ok(minijinja::context! {
                newest,
                posts => &posts,
                months => &months,
                list => Value::from_object(list_obj),
            })
        })
        .collect::<Result<Vec<_>, mailpot::Error>>()?;
    let crumbs = vec![Crumb {
        label: "Home".into(),
        url: "/".into(),
    }];

    let context = minijinja::context! {
        page_title => Option::<&'static str>::None,
        lists => &lists,
        current_user => auth.current_user,
        messages => session.drain_messages(),
        crumbs => crumbs,
    };
    Ok(Html(TEMPLATES.get_template("lists.html")?.render(context)?))
}
source

pub fn list_post_by_message_id( &self, list_pk: i64, message_id: &str ) -> Result<Option<DbVal<Post>>>

Find a post by its Message-ID email header.

source

pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>( &self, render_context: TemplateRenderContext<'ctx, F>, recipients: impl Iterator<Item = Cow<'ctx, Address>> ) -> Result<()>

Helper function to send a template reply.

Examples found in repository?
core/src/posts.rs (lines 235-250)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source§

impl Connection

source

pub fn insert_to_queue(&self, entry: QueueEntry) -> Result<DbVal<QueueEntry>>

Insert a received email into a queue.

Examples found in repository?
cli/src/main.rs (line 624)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (lines 94-100)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
    pub fn post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        let result = self.inner_post(env, raw, _dry_run);
        if let Err(err) = result {
            return match self.insert_to_queue(QueueEntry::new(
                Queue::Error,
                None,
                Some(Cow::Borrowed(env)),
                raw,
                Some(err.to_string()),
            )?) {
                Ok(idx) => {
                    log::info!(
                        "Inserted mail from {:?} into error_queue at index {}",
                        env.from(),
                        idx
                    );
                    Err(err)
                }
                Err(err2) => {
                    log::error!(
                        "Could not insert mail from {:?} into error_queue: {err2}",
                        env.from(),
                    );

                    Err(err.chain_err(|| err2))
                }
            };
        }
        result
    }

    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }

    /// Fetch all year and month values for which at least one post exists in
    /// `yyyy-mm` format.
    pub fn months(&self, list_pk: i64) -> Result<Vec<String>> {
        let mut stmt = self.connection.prepare(
            "SELECT DISTINCT strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') FROM post \
             WHERE list = ?;",
        )?;
        let months_iter = stmt.query_map([list_pk], |row| {
            let val: String = row.get(0)?;
            Ok(val)
        })?;

        let mut ret = vec![];
        for month in months_iter {
            let month = month?;
            ret.push(month);
        }
        Ok(ret)
    }

    /// Find a post by its `Message-ID` email header.
    pub fn list_post_by_message_id(
        &self,
        list_pk: i64,
        message_id: &str,
    ) -> Result<Option<DbVal<Post>>> {
        let mut stmt = self.connection.prepare(
            "SELECT *, strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') AS month_year \
             FROM post WHERE list = ? AND message_id = ?;",
        )?;
        let ret = stmt
            .query_row(rusqlite::params![&list_pk, &message_id], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Post {
                        pk,
                        list: row.get("list")?,
                        envelope_from: row.get("envelope_from")?,
                        address: row.get("address")?,
                        message_id: row.get("message_id")?,
                        message: row.get("message")?,
                        timestamp: row.get("timestamp")?,
                        datetime: row.get("datetime")?,
                        month_year: row.get("month_year")?,
                    },
                    pk,
                ))
            })
            .optional()?;

        Ok(ret)
    }

    /// Helper function to send a template reply.
    pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
        &self,
        render_context: TemplateRenderContext<'ctx, F>,
        recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
    ) -> Result<()> {
        let TemplateRenderContext {
            template,
            default_fn,
            list,
            context,
            queue,
            comment,
        } = render_context;

        let post_policy = self.list_post_policy(list.pk)?;
        let subscription_policy = self.list_subscription_policy(list.pk)?;

        let templ = self
            .fetch_template(template, Some(list.pk))?
            .map(DbVal::into_inner)
            .or_else(|| default_fn.map(|f| f()))
            .ok_or_else(|| -> crate::Error {
                format!("Template with name {template:?} was not found.").into()
            })?;

        let mut draft = templ.render(context)?;
        draft.headers.insert(
            melib::HeaderName::new_unchecked("From"),
            list.request_subaddr(),
        );
        for addr in recipients {
            let mut draft = draft.clone();
            draft
                .headers
                .insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
            list.insert_headers(
                &mut draft,
                post_policy.as_deref(),
                subscription_policy.as_deref(),
            );
            self.insert_to_queue(QueueEntry::new(
                queue,
                Some(list.pk),
                None,
                draft.finalise()?.as_bytes(),
                Some(comment.to_string()),
            )?)?;
        }
        Ok(())
    }
source

pub fn queue(&self, queue: Queue) -> Result<Vec<DbVal<QueueEntry>>>

Fetch all queue entries.

Examples found in repository?
cli/src/main.rs (line 544)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn delete_from_queue( &self, queue: Queue, index: Vec<i64> ) -> Result<Vec<QueueEntry>>

Delete queue entries returning the deleted values.

Examples found in repository?
cli/src/main.rs (line 554)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source§

impl Connection

source

pub fn new_smtp_connection( &self ) -> Result<Pin<Box<dyn Future<Output = Result<SmtpConnection>> + Send + 'static>>>

Return an SMTP connection handle if the database connection has one configured.

Examples found in repository?
cli/src/main.rs (line 607)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub async fn submit( smtp_connection: &mut SmtpConnection, message: &QueueEntry, dry_run: bool ) -> Result<()>

Submit queue items from values to their recipients.

Examples found in repository?
cli/src/main.rs (line 611)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source§

impl Connection

source

pub fn list_subscriptions( &self, pk: i64 ) -> Result<Vec<DbVal<ListSubscription>>>

Fetch all subscriptions of a mailing list.

Examples found in repository?
cli/src/main.rs (line 110)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 177)
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
    fn inner_post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
                filter_settings: self.get_settings(list.pk)?,
                list: &mut list,
            };
            let mut post = PostEntry {
                message_id: env.message_id().clone(),
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let PostEntry { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    /* error handled by notifying submitter */
                    return Ok(());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Ok(());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }
source

pub fn list_subscription( &self, list_pk: i64, pk: i64 ) -> Result<DbVal<ListSubscription>>

Fetch mailing list subscription.

Examples found in repository?
core/src/subscriptions.rs (line 186)
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
    pub fn add_subscription(
        &self,
        list_pk: i64,
        mut new_val: ListSubscription,
    ) -> Result<DbVal<ListSubscription>> {
        new_val.list = list_pk;
        let mut stmt = self
            .connection
            .prepare(
                "INSERT INTO subscription(list, address, account, name, enabled, digest, \
                 verified, hide_address, receive_duplicates, receive_own_posts, \
                 receive_confirmation) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *;",
            )
            .unwrap();
        let val = stmt.query_row(
            rusqlite::params![
                &new_val.list,
                &new_val.address,
                &new_val.account,
                &new_val.name,
                &new_val.enabled,
                &new_val.digest,
                &new_val.verified,
                &new_val.hide_address,
                &new_val.receive_duplicates,
                &new_val.receive_own_posts,
                &new_val.receive_confirmation
            ],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        account: row.get("account")?,
                        digest: row.get("digest")?,
                        enabled: row.get("enabled")?,
                        verified: row.get("verified")?,
                        hide_address: row.get("hide_address")?,
                        receive_duplicates: row.get("receive_duplicates")?,
                        receive_own_posts: row.get("receive_own_posts")?,
                        receive_confirmation: row.get("receive_confirmation")?,
                    },
                    pk,
                ))
            },
        )?;
        trace!("add_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        self.list_subscription(list_pk, val.pk())
    }

    /// Create subscription candidate.
    pub fn add_candidate_subscription(
        &self,
        list_pk: i64,
        mut new_val: ListSubscription,
    ) -> Result<DbVal<ListCandidateSubscription>> {
        new_val.list = list_pk;
        let mut stmt = self.connection.prepare(
            "INSERT INTO candidate_subscription(list, address, name, accepted) VALUES(?, ?, ?, ?) \
             RETURNING *;",
        )?;
        let val = stmt.query_row(
            rusqlite::params![&new_val.list, &new_val.address, &new_val.name, None::<i64>,],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListCandidateSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        accepted: row.get("accepted")?,
                    },
                    pk,
                ))
            },
        )?;
        drop(stmt);

        trace!("add_candidate_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        self.candidate_subscription(val.pk())
    }

    /// Fetch subscription candidate by primary key.
    pub fn candidate_subscription(&self, pk: i64) -> Result<DbVal<ListCandidateSubscription>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM candidate_subscription WHERE pk = ?;")?;
        let val = stmt
            .query_row(rusqlite::params![&pk], |row| {
                let _pk: i64 = row.get("pk")?;
                debug_assert_eq!(pk, _pk);
                Ok(DbVal(
                    ListCandidateSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        accepted: row.get("accepted")?,
                    },
                    pk,
                ))
            })
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err)
                        .chain_err(|| NotFound("Candidate subscription with this pk not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(val)
    }

    /// Accept subscription candidate.
    pub fn accept_candidate_subscription(&self, pk: i64) -> Result<DbVal<ListSubscription>> {
        let val = self.connection.query_row(
            "INSERT INTO subscription(list, address, name, enabled, digest, verified, \
             hide_address, receive_duplicates, receive_own_posts, receive_confirmation) SELECT \
             list, address, name, 1, 0, 0, 0, 1, 1, 0 FROM candidate_subscription WHERE pk = ? \
             RETURNING *;",
            rusqlite::params![&pk],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        account: row.get("account")?,
                        name: row.get("name")?,
                        digest: row.get("digest")?,
                        enabled: row.get("enabled")?,
                        verified: row.get("verified")?,
                        hide_address: row.get("hide_address")?,
                        receive_duplicates: row.get("receive_duplicates")?,
                        receive_own_posts: row.get("receive_own_posts")?,
                        receive_confirmation: row.get("receive_confirmation")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("accept_candidate_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        let ret = self.list_subscription(val.list, val.pk())?;

        // assert that [ref:accept_candidate] trigger works.
        debug_assert_eq!(Some(ret.pk), self.candidate_subscription(pk)?.accepted);
        Ok(ret)
    }
source

pub fn list_subscription_by_address( &self, list_pk: i64, address: &str ) -> Result<DbVal<ListSubscription>>

Fetch mailing list subscription by their address.

Examples found in repository?
core/src/subscriptions.rs (line 316)
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
    pub fn update_subscription(&self, change_set: ListSubscriptionChangeset) -> Result<()> {
        let pk = self
            .list_subscription_by_address(change_set.list, &change_set.address)?
            .pk;
        if matches!(
            change_set,
            ListSubscriptionChangeset {
                list: _,
                address: _,
                account: None,
                name: None,
                digest: None,
                verified: None,
                hide_address: None,
                receive_duplicates: None,
                receive_own_posts: None,
                receive_confirmation: None,
                enabled: None,
            }
        ) {
            return Ok(());
        }

        let ListSubscriptionChangeset {
            list,
            address: _,
            name,
            account,
            digest,
            enabled,
            verified,
            hide_address,
            receive_duplicates,
            receive_own_posts,
            receive_confirmation,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_subscription)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!(
                            "UPDATE subscription SET ",
                            stringify!($field),
                            " = ? WHERE list = ? AND pk = ?;"
                        ),
                        rusqlite::params![&$field, &list, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(account);
        update!(digest);
        update!(enabled);
        update!(verified);
        update!(hide_address);
        update!(receive_duplicates);
        update!(receive_own_posts);
        update!(receive_confirmation);

        tx.commit()?;
        Ok(())
    }
More examples
Hide additional examples
core/src/posts.rs (line 353)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn add_subscription( &self, list_pk: i64, new_val: ListSubscription ) -> Result<DbVal<ListSubscription>>

Add subscription to mailing list.

Examples found in repository?
cli/src/main.rs (lines 177-193)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 456)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn add_candidate_subscription( &self, list_pk: i64, new_val: ListSubscription ) -> Result<DbVal<ListCandidateSubscription>>

Create subscription candidate.

Examples found in repository?
core/src/posts.rs (line 390)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn candidate_subscription( &self, pk: i64 ) -> Result<DbVal<ListCandidateSubscription>>

Fetch subscription candidate by primary key.

Examples found in repository?
core/src/subscriptions.rs (line 220)
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
    pub fn add_candidate_subscription(
        &self,
        list_pk: i64,
        mut new_val: ListSubscription,
    ) -> Result<DbVal<ListCandidateSubscription>> {
        new_val.list = list_pk;
        let mut stmt = self.connection.prepare(
            "INSERT INTO candidate_subscription(list, address, name, accepted) VALUES(?, ?, ?, ?) \
             RETURNING *;",
        )?;
        let val = stmt.query_row(
            rusqlite::params![&new_val.list, &new_val.address, &new_val.name, None::<i64>,],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListCandidateSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        accepted: row.get("accepted")?,
                    },
                    pk,
                ))
            },
        )?;
        drop(stmt);

        trace!("add_candidate_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        self.candidate_subscription(val.pk())
    }

    /// Fetch subscription candidate by primary key.
    pub fn candidate_subscription(&self, pk: i64) -> Result<DbVal<ListCandidateSubscription>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM candidate_subscription WHERE pk = ?;")?;
        let val = stmt
            .query_row(rusqlite::params![&pk], |row| {
                let _pk: i64 = row.get("pk")?;
                debug_assert_eq!(pk, _pk);
                Ok(DbVal(
                    ListCandidateSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        accepted: row.get("accepted")?,
                    },
                    pk,
                ))
            })
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err)
                        .chain_err(|| NotFound("Candidate subscription with this pk not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(val)
    }

    /// Accept subscription candidate.
    pub fn accept_candidate_subscription(&self, pk: i64) -> Result<DbVal<ListSubscription>> {
        let val = self.connection.query_row(
            "INSERT INTO subscription(list, address, name, enabled, digest, verified, \
             hide_address, receive_duplicates, receive_own_posts, receive_confirmation) SELECT \
             list, address, name, 1, 0, 0, 0, 1, 1, 0 FROM candidate_subscription WHERE pk = ? \
             RETURNING *;",
            rusqlite::params![&pk],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        account: row.get("account")?,
                        name: row.get("name")?,
                        digest: row.get("digest")?,
                        enabled: row.get("enabled")?,
                        verified: row.get("verified")?,
                        hide_address: row.get("hide_address")?,
                        receive_duplicates: row.get("receive_duplicates")?,
                        receive_own_posts: row.get("receive_own_posts")?,
                        receive_confirmation: row.get("receive_confirmation")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("accept_candidate_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        let ret = self.list_subscription(val.list, val.pk())?;

        // assert that [ref:accept_candidate] trigger works.
        debug_assert_eq!(Some(ret.pk), self.candidate_subscription(pk)?.accepted);
        Ok(ret)
    }
source

pub fn accept_candidate_subscription( &self, pk: i64 ) -> Result<DbVal<ListSubscription>>

Accept subscription candidate.

source

pub fn remove_subscription(&self, list_pk: i64, address: &str) -> Result<()>

Remove a subscription by their address.

Examples found in repository?
cli/src/main.rs (line 212)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 522)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn update_subscription( &self, change_set: ListSubscriptionChangeset ) -> Result<()>

Update a mailing list subscription.

Examples found in repository?
cli/src/main.rs (line 305)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn account(&self, pk: i64) -> Result<Option<DbVal<Account>>>

Fetch account by pk.

source

pub fn account_by_address( &self, address: &str ) -> Result<Option<DbVal<Account>>>

Fetch account by address.

Examples found in repository?
cli/src/main.rs (line 831)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/subscriptions.rs (line 551)
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    pub fn update_account(&self, change_set: AccountChangeset) -> Result<()> {
        let Some(acc) = self.account_by_address(&change_set.address)? else {
            return Err(NotFound("account with this address not found!").into());
        };
        let pk = acc.pk;
        if matches!(
            change_set,
            AccountChangeset {
                address: _,
                name: None,
                public_key: None,
                password: None,
                enabled: None,
            }
        ) {
            return Ok(());
        }

        let AccountChangeset {
            address: _,
            name,
            public_key,
            password,
            enabled,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_account)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!(
                            "UPDATE account SET ",
                            stringify!($field),
                            " = ? WHERE pk = ?;"
                        ),
                        rusqlite::params![&$field, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(public_key);
        update!(password);
        update!(enabled);

        tx.commit()?;
        Ok(())
    }
core/src/posts.rs (line 605)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn account_subscriptions( &self, pk: i64 ) -> Result<Vec<DbVal<ListSubscription>>>

Fetch all subscriptions of an account by primary key.

Examples found in repository?
cli/src/main.rs (line 832)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn accounts(&self) -> Result<Vec<DbVal<Account>>>

Fetch all accounts.

Examples found in repository?
cli/src/main.rs (line 821)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn add_account(&self, new_val: Account) -> Result<DbVal<Account>>

Add account.

Examples found in repository?
cli/src/main.rs (lines 867-874)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (lines 618-625)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source

pub fn remove_account(&self, address: &str) -> Result<()>

Remove an account by their address.

Examples found in repository?
cli/src/main.rs (line 892)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
source

pub fn update_account(&self, change_set: AccountChangeset) -> Result<()>

Update an account.

Examples found in repository?
cli/src/main.rs (line 908)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
fn run_app(opt: Opt) -> Result<()> {
    if opt.debug {
        println!("DEBUG: {:?}", &opt);
    }
    if let Command::SampleConfig { with_smtp } = opt.cmd {
        let mut new = Configuration::new("/path/to/sqlite.db");
        new.administrators.push("admin@example.com".to_string());
        if with_smtp {
            new.send_mail = mailpot::SendMail::Smtp(SmtpServerConf {
                hostname: "mail.example.com".to_string(),
                port: 587,
                envelope_from: "".to_string(),
                auth: SmtpAuth::Auto {
                    username: "user".to_string(),
                    password: Password::Raw("hunter2".to_string()),
                    auth_type: SmtpAuthType::default(),
                    require_auth: true,
                },
                security: SmtpSecurity::StartTLS {
                    danger_accept_invalid_certs: false,
                },
                extensions: Default::default(),
            });
        }
        println!("{}", new.to_toml());
        return Ok(());
    };
    let config_path = if let Some(path) = opt.config.as_ref() {
        path.as_path()
    } else {
        let mut opt = Opt::command();
        opt.error(
            clap::error::ErrorKind::MissingRequiredArgument,
            "--config is required for mailing list operations",
        )
        .exit();
    };

    let config = Configuration::from_file(config_path)?;

    use Command::*;
    let mut db = Connection::open_or_create_db(config)?.trusted();
    match opt.cmd {
        SampleConfig { .. } => {}
        DumpDatabase => {
            let lists = db.lists()?;
            let mut stdout = std::io::stdout();
            serde_json::to_writer_pretty(&mut stdout, &lists)?;
            for l in &lists {
                serde_json::to_writer_pretty(&mut stdout, &db.list_subscriptions(l.pk)?)?;
            }
        }
        ListLists => {
            let lists = db.lists()?;
            if lists.is_empty() {
                println!("No lists found.");
            } else {
                for l in lists {
                    println!("- {} {:?}", l.id, l);
                    let list_owners = db.list_owners(l.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList owners: None");
                    } else {
                        println!("\tList owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = db.list_post_policy(l.pk)? {
                        println!("\tPost policy: {}", s);
                    } else {
                        println!("\tPost policy: None");
                    }
                    if let Some(s) = db.list_subscription_policy(l.pk)? {
                        println!("\tSubscription policy: {}", s);
                    } else {
                        println!("\tSubscription policy: None");
                    }
                    println!();
                }
            }
        }
        List { list_id, cmd } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            use ListCommand::*;
            match cmd {
                Subscriptions => {
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions found.");
                    } else {
                        println!("Subscriptions of list {}", list.id);
                        for l in subscriptions {
                            println!("- {}", &l);
                        }
                    }
                }
                AddSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    db.add_subscription(
                        list.pk,
                        ListSubscription {
                            pk: 0,
                            list: list.pk,
                            address,
                            account: None,
                            name,
                            digest: digest.unwrap_or(false),
                            hide_address: hide_address.unwrap_or(false),
                            receive_confirmation: receive_confirmation.unwrap_or(true),
                            receive_duplicates: receive_duplicates.unwrap_or(true),
                            receive_own_posts: receive_own_posts.unwrap_or(false),
                            enabled: enabled.unwrap_or(true),
                            verified: verified.unwrap_or(false),
                        },
                    )?;
                }
                RemoveSubscription { address } => {
                    let mut input = String::new();
                    loop {
                        println!(
                            "Are you sure you want to remove subscription of {} from list {}? \
                             [Yy/n]",
                            address, list
                        );
                        input.clear();
                        std::io::stdin().read_line(&mut input)?;
                        if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                            break;
                        } else if input.trim() == "n" {
                            return Ok(());
                        }
                    }

                    db.remove_subscription(list.pk, &address)?;
                }
                Health => {
                    println!("{} health:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    if list_owners.is_empty() {
                        println!("\tList has no owners: you should add at least one.");
                    } else {
                        for owner in list_owners {
                            println!("\tList owner: {}.", owner);
                        }
                    }
                    if let Some(p) = post_policy {
                        println!("\tList has post policy: {p}.");
                    } else {
                        println!("\tList has no post policy: you should add one.");
                    }
                    if let Some(p) = subscription_policy {
                        println!("\tList has subscription policy: {p}.");
                    } else {
                        println!("\tList has no subscription policy: you should add one.");
                    }
                }
                Info => {
                    println!("{} info:", list);
                    let list_owners = db.list_owners(list.pk)?;
                    let post_policy = db.list_post_policy(list.pk)?;
                    let subscription_policy = db.list_subscription_policy(list.pk)?;
                    let subscriptions = db.list_subscriptions(list.pk)?;
                    if subscriptions.is_empty() {
                        println!("No subscriptions.");
                    } else if subscriptions.len() == 1 {
                        println!("1 subscription.");
                    } else {
                        println!("{} subscriptions.", subscriptions.len());
                    }
                    if list_owners.is_empty() {
                        println!("List owners: None");
                    } else {
                        println!("List owners:");
                        for o in list_owners {
                            println!("\t- {}", o);
                        }
                    }
                    if let Some(s) = post_policy {
                        println!("Post policy: {s}");
                    } else {
                        println!("Post policy: None");
                    }
                    if let Some(s) = subscription_policy {
                        println!("Subscription policy: {s}");
                    } else {
                        println!("Subscription policy: None");
                    }
                }
                UpdateSubscription {
                    address,
                    subscription_options:
                        SubscriptionOptions {
                            name,
                            digest,
                            hide_address,
                            receive_duplicates,
                            receive_own_posts,
                            receive_confirmation,
                            enabled,
                            verified,
                        },
                } => {
                    let name = if name
                        .as_ref()
                        .map(|s: &String| s.is_empty())
                        .unwrap_or(false)
                    {
                        None
                    } else {
                        Some(name)
                    };
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name,
                        digest,
                        verified,
                        hide_address,
                        receive_duplicates,
                        receive_own_posts,
                        receive_confirmation,
                        enabled,
                    };
                    db.update_subscription(changeset)?;
                }
                AddPostPolicy {
                    announce_only,
                    subscription_only,
                    approval_needed,
                    open,
                    custom,
                } => {
                    let policy = PostPolicy {
                        pk: 0,
                        list: list.pk,
                        announce_only,
                        subscription_only,
                        approval_needed,
                        open,
                        custom,
                    };
                    let new_val = db.set_list_post_policy(policy)?;
                    println!("Added new policy with pk = {}", new_val.pk());
                }
                RemovePostPolicy { pk } => {
                    db.remove_list_post_policy(list.pk, pk)?;
                    println!("Removed policy with pk = {}", pk);
                }
                AddSubscriptionPolicy {
                    send_confirmation,
                    open,
                    manual,
                    request,
                    custom,
                } => {
                    let policy = SubscriptionPolicy {
                        pk: 0,
                        list: list.pk,
                        send_confirmation,
                        open,
                        manual,
                        request,
                        custom,
                    };
                    let new_val = db.set_list_subscription_policy(policy)?;
                    println!("Added new subscribe policy with pk = {}", new_val.pk());
                }
                RemoveSubscriptionPolicy { pk } => {
                    db.remove_list_subscription_policy(list.pk, pk)?;
                    println!("Removed subscribe policy with pk = {}", pk);
                }
                AddListOwner { address, name } => {
                    let list_owner = ListOwner {
                        pk: 0,
                        list: list.pk,
                        address,
                        name,
                    };
                    let new_val = db.add_list_owner(list_owner)?;
                    println!("Added new list owner {}", new_val);
                }
                RemoveListOwner { pk } => {
                    db.remove_list_owner(list.pk, pk)?;
                    println!("Removed list owner with pk = {}", pk);
                }
                EnableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        verified: None,
                        enabled: Some(true),
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                DisableSubscription { address } => {
                    let changeset = ListSubscriptionChangeset {
                        list: list.pk,
                        address,
                        account: None,
                        name: None,
                        digest: None,
                        enabled: Some(false),
                        verified: None,
                        hide_address: None,
                        receive_duplicates: None,
                        receive_own_posts: None,
                        receive_confirmation: None,
                    };
                    db.update_subscription(changeset)?;
                }
                Update {
                    name,
                    id,
                    address,
                    description,
                    archive_url,
                    owner_local_part,
                    request_local_part,
                    verify,
                    hidden,
                    enabled,
                } => {
                    let description = string_opts!(description);
                    let archive_url = string_opts!(archive_url);
                    let owner_local_part = string_opts!(owner_local_part);
                    let request_local_part = string_opts!(request_local_part);
                    let changeset = MailingListChangeset {
                        pk: list.pk,
                        name,
                        id,
                        address,
                        description,
                        archive_url,
                        owner_local_part,
                        request_local_part,
                        verify,
                        hidden,
                        enabled,
                    };
                    db.update_list(changeset)?;
                }
                ImportMembers {
                    url,
                    username,
                    password,
                    list_id,
                    dry_run,
                    skip_owners,
                } => {
                    let conn = import::Mailman3Connection::new(&url, &username, &password).unwrap();
                    if dry_run {
                        let entries = conn.users(&list_id).unwrap();
                        println!("{} result(s)", entries.len());
                        for e in entries {
                            println!(
                                "{}{}<{}>",
                                if let Some(n) = e.display_name() {
                                    n
                                } else {
                                    ""
                                },
                                if e.display_name().is_none() { "" } else { " " },
                                e.email()
                            );
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            println!("\nOwners: {} result(s)", entries.len());
                            for e in entries {
                                println!(
                                    "{}{}<{}>",
                                    if let Some(n) = e.display_name() {
                                        n
                                    } else {
                                        ""
                                    },
                                    if e.display_name().is_none() { "" } else { " " },
                                    e.email()
                                );
                            }
                        }
                    } else {
                        let entries = conn.users(&list_id).unwrap();
                        let tx = db.transaction(Default::default()).unwrap();
                        for sub in entries.into_iter().map(|e| e.into_subscription(list.pk)) {
                            tx.add_subscription(list.pk, sub)?;
                        }
                        if !skip_owners {
                            let entries = conn.owners(&list_id).unwrap();
                            for sub in entries.into_iter().map(|e| e.into_owner(list.pk)) {
                                tx.add_list_owner(sub)?;
                            }
                        }
                        tx.commit()?;
                    }
                }
            }
        }
        CreateList {
            name,
            id,
            address,
            description,
            archive_url,
        } => {
            let new = db.create_list(MailingList {
                pk: 0,
                name,
                id,
                description,
                topics: vec![],
                address,
                archive_url,
            })?;
            log::trace!("created new list {:#?}", new);
            if !opt.quiet {
                println!(
                    "Created new list {:?} with primary key {}",
                    new.id,
                    new.pk()
                );
            }
        }
        Post { dry_run } => {
            if opt.debug {
                println!("post dry_run{:?}", dry_run);
            }

            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input)?;
            match Envelope::from_bytes(input.as_bytes(), None) {
                Ok(env) => {
                    if opt.debug {
                        eprintln!("{:?}", &env);
                    }
                    tx.post(&env, input.as_bytes(), dry_run)?;
                }
                Err(err) if input.trim().is_empty() => {
                    eprintln!("Empty input, abort.");
                    return Err(err.into());
                }
                Err(err) => {
                    eprintln!("Could not parse message: {}", err);
                    let p = tx.conf().save_message(input)?;
                    eprintln!("Message saved at {}", p.display());
                    return Err(err.into());
                }
            }
            tx.commit()?;
        }
        FlushQueue { dry_run } => {
            let tx = db.transaction(TransactionBehavior::Exclusive).unwrap();
            let messages = if opt.debug {
                println!("flush-queue dry_run {:?}", dry_run);
                tx.queue(mailpot::queue::Queue::Out)?
                    .into_iter()
                    .map(DbVal::into_inner)
                    .chain(
                        tx.queue(mailpot::queue::Queue::Deferred)?
                            .into_iter()
                            .map(DbVal::into_inner),
                    )
                    .collect()
            } else {
                tx.delete_from_queue(mailpot::queue::Queue::Out, vec![])?
            };
            if opt.verbose > 0 || opt.debug {
                println!("Queue out has {} messages.", messages.len());
            }

            let mut failures = Vec::with_capacity(messages.len());

            let send_mail = tx.conf().send_mail.clone();
            match send_mail {
                mailpot::SendMail::ShellCommand(cmd) => {
                    fn submit(cmd: &str, msg: &QueueEntry) -> Result<()> {
                        let mut child = std::process::Command::new("sh")
                            .arg("-c")
                            .arg(cmd)
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn()
                            .context("sh command failed to start")?;
                        let mut stdin = child.stdin.take().context("Failed to open stdin")?;

                        let builder = std::thread::Builder::new();

                        std::thread::scope(|s| {
                            let handler = builder
                                .spawn_scoped(s, move || {
                                    stdin
                                        .write_all(&msg.message)
                                        .expect("Failed to write to stdin");
                                })
                                .context(
                                    "Could not spawn IPC communication thread for SMTP \
                                     ShellCommand process",
                                )?;

                            handler.join().map_err(|_| {
                                ErrorKind::External(mailpot::anyhow::anyhow!(
                                    "Could not join with IPC communication thread for SMTP \
                                     ShellCommand process"
                                ))
                            })?;
                            Ok::<(), Error>(())
                        })?;
                        Ok(())
                    }
                    for msg in messages {
                        if let Err(err) = submit(&cmd, &msg) {
                            failures.push((err, msg));
                        }
                    }
                }
                mailpot::SendMail::Smtp(_) => {
                    let conn_future = tx.new_smtp_connection()?;
                    failures = smol::future::block_on(smol::spawn(async move {
                        let mut conn = conn_future.await?;
                        for msg in messages {
                            if let Err(err) = Connection::submit(&mut conn, &msg, dry_run).await {
                                failures.push((err, msg));
                            }
                        }
                        Ok::<_, Error>(failures)
                    }))?;
                }
            }

            for (err, mut msg) in failures {
                log::error!("Message {msg:?} failed with: {err}. Inserting to Deferred queue.");

                msg.queue = mailpot::queue::Queue::Deferred;
                tx.insert_to_queue(msg)?;
            }

            tx.commit()?;
        }
        ErrorQueue { cmd } => match cmd {
            QueueCommand::List => {
                let errors = db.queue(mailpot::queue::Queue::Error)?;
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    println!("Error queue is empty.");
                } else {
                    for e in errors {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut errors = db.queue(mailpot::queue::Queue::Error)?;
                if !index.is_empty() {
                    errors.retain(|el| index.contains(&el.pk()));
                }
                if errors.is_empty() {
                    if !quiet {
                        println!("Error queue is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting error queue elements {:?}", &index);
                    }
                    db.delete_from_queue(mailpot::queue::Queue::Error, index)?;
                    if !quiet {
                        for e in errors {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        Queue { queue, cmd } => match cmd {
            QueueCommand::List => {
                let entries = db.queue(queue)?;
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!(
                            "- {} {} {} {} {}",
                            e.pk, e.datetime, e.from_address, e.to_addresses, e.subject
                        );
                    }
                }
            }
            QueueCommand::Print { index } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    println!("Queue {queue} is empty.");
                } else {
                    for e in entries {
                        println!("{e:?}");
                    }
                }
            }
            QueueCommand::Delete { index, quiet } => {
                let mut entries = db.queue(queue)?;
                if !index.is_empty() {
                    entries.retain(|el| index.contains(&el.pk()));
                }
                if entries.is_empty() {
                    if !quiet {
                        println!("Queue {queue} is empty.");
                    }
                } else {
                    if !quiet {
                        println!("Deleting queue {queue} elements {:?}", &index);
                    }
                    db.delete_from_queue(queue, index)?;
                    if !quiet {
                        for e in entries {
                            println!("{e:?}");
                        }
                    }
                }
            }
        },
        ImportMaildir {
            list_id,
            mut maildir_path,
        } => {
            let list = match list!(db, list_id) {
                Some(v) => v,
                None => {
                    return Err(format!("No list with id or pk {} was found", list_id).into());
                }
            };
            if !maildir_path.is_absolute() {
                maildir_path = std::env::current_dir()
                    .expect("could not detect current directory")
                    .join(&maildir_path);
            }

            fn get_file_hash(file: &std::path::Path) -> EnvelopeHash {
                let mut hasher = DefaultHasher::default();
                file.hash(&mut hasher);
                EnvelopeHash(hasher.finish())
            }
            let mut buf = Vec::with_capacity(4096);
            let files =
                melib::backends::maildir::MaildirType::list_mail_in_maildir_fs(maildir_path, true)?;
            let mut ctr = 0;
            for file in files {
                let hash = get_file_hash(&file);
                let mut reader = std::io::BufReader::new(std::fs::File::open(&file)?);
                buf.clear();
                reader.read_to_end(&mut buf)?;
                if let Ok(mut env) = Envelope::from_bytes(buf.as_slice(), Some(file.flags())) {
                    env.set_hash(hash);
                    db.insert_post(list.pk, &buf, &env)?;
                    ctr += 1;
                }
            }
            println!("Inserted {} posts to {}.", ctr, list_id);
        }
        UpdatePostfixConfig {
            master_cf,
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            pfconf.save_maps(db.conf())?;
            pfconf.save_master_cf_entry(db.conf(), config_path, master_cf.as_deref())?;
        }
        PrintPostfixConfig {
            config:
                PostfixConfig {
                    user,
                    group,
                    binary_path,
                    process_limit,
                    map_output_path,
                    transport_name,
                },
        } => {
            let pfconf = mailpot::postfix::PostfixConfiguration {
                user: user.into(),
                group: group.map(Into::into),
                binary_path,
                process_limit,
                map_output_path,
                transport_name: transport_name.map(std::borrow::Cow::from),
            };
            let lists = db.lists()?;
            let lists_post_policies = lists
                .into_iter()
                .map(|l| {
                    let pk = l.pk;
                    Ok((l, db.list_post_policy(pk)?))
                })
                .collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
            let maps = pfconf.generate_maps(&lists_post_policies);
            let mastercf = pfconf.generate_master_cf_entry(db.conf(), config_path);

            println!("{maps}\n\n{mastercf}\n");
        }
        Accounts => {
            let accounts = db.accounts()?;
            if accounts.is_empty() {
                println!("No accounts found.");
            } else {
                for a in accounts {
                    println!("- {:?}", a);
                }
            }
        }
        AccountInfo { address } => {
            if let Some(acc) = db.account_by_address(&address)? {
                let subs = db.account_subscriptions(acc.pk())?;
                if subs.is_empty() {
                    println!("No subscriptions found.");
                } else {
                    for s in subs {
                        let list = db
                            .list(s.list)
                            .unwrap_or_else(|err| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}\n\n{err}",
                                    s.list, s
                                )
                            })
                            .unwrap_or_else(|| {
                                panic!(
                                    "Found subscription with list_pk = {} but no such list \
                                     exists.\nListSubscription = {:?}",
                                    s.list, s
                                )
                            });
                        println!("- {:?} {}", s, list);
                    }
                }
            } else {
                println!("account with this address not found!");
            };
        }
        AddAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            db.add_account(Account {
                pk: 0,
                name,
                address,
                public_key,
                password,
                enabled: enabled.unwrap_or(true),
            })?;
        }
        RemoveAccount { address } => {
            let mut input = String::new();
            loop {
                println!(
                    "Are you sure you want to remove account with address {}? [Yy/n]",
                    address
                );
                input.clear();
                std::io::stdin().read_line(&mut input)?;
                if input.trim() == "Y" || input.trim() == "y" || input.trim() == "" {
                    break;
                } else if input.trim() == "n" {
                    return Ok(());
                }
            }

            db.remove_account(&address)?;
        }
        UpdateAccount {
            address,
            password,
            name,
            public_key,
            enabled,
        } => {
            let changeset = AccountChangeset {
                address,
                name,
                public_key,
                password,
                enabled,
            };
            db.update_account(changeset)?;
        }
        Repair {
            fix,
            all,
            mut datetime_header_value,
            mut remove_empty_accounts,
            mut remove_accepted_subscription_requests,
            mut warn_list_no_owner,
        } => {
            type LintFn =
                fn(&'_ mut mailpot::Connection, bool) -> std::result::Result<(), mailpot::Error>;
            let dry_run = !fix;
            if all {
                datetime_header_value = true;
                remove_empty_accounts = true;
                remove_accepted_subscription_requests = true;
                warn_list_no_owner = true;
            }

            if !(datetime_header_value
                | remove_empty_accounts
                | remove_accepted_subscription_requests
                | warn_list_no_owner)
            {
                return Err(
                    "No lints selected: specify them with flag arguments. See --help".into(),
                );
            }

            if dry_run {
                println!("running without making modifications (dry run)");
            }

            for (flag, lint_fn) in [
                (datetime_header_value, datetime_header_value_lint as LintFn),
                (remove_empty_accounts, remove_empty_accounts_lint as _),
                (
                    remove_accepted_subscription_requests,
                    remove_accepted_subscription_requests_lint as _,
                ),
                (warn_list_no_owner, warn_list_no_owner_lint as _),
            ] {
                if flag {
                    lint_fn(&mut db, dry_run)?;
                }
            }
        }
    }

    Ok(())
}
More examples
Hide additional examples
core/src/posts.rs (line 614)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
    pub fn request(
        &self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }
source§

impl Connection

source

pub fn fetch_templates(&self) -> Result<Vec<DbVal<Template>>>

Fetch all.

source

pub fn fetch_template( &self, template: &str, list_pk: Option<i64> ) -> Result<Option<DbVal<Template>>>

Fetch a named template.

Examples found in repository?
core/src/posts.rs (line 737)
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
    pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
        &self,
        render_context: TemplateRenderContext<'ctx, F>,
        recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
    ) -> Result<()> {
        let TemplateRenderContext {
            template,
            default_fn,
            list,
            context,
            queue,
            comment,
        } = render_context;

        let post_policy = self.list_post_policy(list.pk)?;
        let subscription_policy = self.list_subscription_policy(list.pk)?;

        let templ = self
            .fetch_template(template, Some(list.pk))?
            .map(DbVal::into_inner)
            .or_else(|| default_fn.map(|f| f()))
            .ok_or_else(|| -> crate::Error {
                format!("Template with name {template:?} was not found.").into()
            })?;

        let mut draft = templ.render(context)?;
        draft.headers.insert(
            melib::HeaderName::new_unchecked("From"),
            list.request_subaddr(),
        );
        for addr in recipients {
            let mut draft = draft.clone();
            draft
                .headers
                .insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
            list.insert_headers(
                &mut draft,
                post_policy.as_deref(),
                subscription_policy.as_deref(),
            );
            self.insert_to_queue(QueueEntry::new(
                queue,
                Some(list.pk),
                None,
                draft.finalise()?.as_bytes(),
                Some(comment.to_string()),
            )?)?;
        }
        Ok(())
    }
source

pub fn add_template(&self, template: Template) -> Result<DbVal<Template>>

Insert a named template.

source

pub fn remove_template( &self, template: &str, list_pk: Option<i64> ) -> Result<Template>

Remove a named template.

Trait Implementations§

source§

impl Debug for Connection

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Connection

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.