Skip to main content

laravel_mailing_list/
lib.rs

1//! Mailing lists for [Laravel Rust](https://crates.io/crates/laravel-rust): double opt-in
2//! subscriptions with a consent record, one-click unsubscribe, and a suppression list, kept in your
3//! own database.
4//!
5//! Declare your lists in `src/app.rs` and run `laravel migrate`:
6//!
7//! ```no_run
8//! use laravel::Application;
9//! use laravel_mailing_list::{List, MailingListServiceProvider};
10//!
11//! # let _ =
12//! Application::configure().with_providers(|providers| {
13//!     providers.add(MailingListServiceProvider::new().list("blog", List::local().name("AxVi blog")));
14//! })
15//! # ;
16//! ```
17//!
18//! Then a form that posts `email` to `/mailing-list/blog/subscribe` starts a subscription, and
19//! code does the same with [`lists::get`]:
20//!
21//! ```no_run
22//! # async fn run() -> laravel::Result<()> {
23//! use laravel_mailing_list::{Subscription, lists};
24//!
25//! let blog = lists::get("blog").await?;
26//! blog.subscribe(Subscription::new("ann@example.com").name("Ann").source("footer")).await?;
27//! # Ok(())
28//! # }
29//! ```
30
31mod campaigns;
32mod commands;
33mod config;
34mod email;
35pub mod events;
36pub mod lists;
37mod local;
38#[cfg(feature = "mailchimp")]
39mod mailchimp;
40pub mod models;
41mod render;
42mod routes;
43#[cfg(feature = "template-engine")]
44pub mod templates;
45pub mod transfer;
46
47use std::collections::BTreeMap;
48use std::sync::Arc;
49
50use laravel::config::{Config, Env};
51use laravel::container::Registrar;
52use laravel::foundation::ServiceProvider;
53
54pub use crate::campaigns::{CampaignDraft, CampaignMail, PrepareCampaign, SendDeliveries, Stats};
55pub use crate::config::MailingListConfig;
56pub use crate::email::Email;
57pub use crate::lists::{Driver, List, ListConfig, ListHandle, Subscribed, Subscription};
58pub use crate::local::ConfirmSubscription;
59pub use crate::routes::{SubscribeForm, confirm, subscribe, unsubscribe, unsubscribe_page};
60
61use crate::lists::Lists;
62
63/// Adds the package's settings, tables, pages and emails, and the lists you declare.
64#[derive(Clone, Debug, Default)]
65pub struct MailingListServiceProvider {
66    lists: BTreeMap<String, ListConfig>,
67    #[cfg(feature = "template-engine")]
68    template_engine: bool,
69}
70
71impl MailingListServiceProvider {
72    /// The provider with no lists yet.
73    #[must_use]
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Declares the list `key`, such as `blog`. The key goes in URLs and in the database, so keep it
79    /// short and stable: letters, digits, `-` and `_`.
80    ///
81    /// # Panics
82    ///
83    /// When `key` is empty, longer than 64 characters, has other characters, or is declared twice.
84    #[must_use]
85    pub fn list(mut self, key: impl Into<String>, list: List) -> Self {
86        let key = key.into();
87        assert!(
88            !key.is_empty()
89                && key.len() <= 64
90                && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
91            "the mailing list key `{key}` must be 1 to 64 letters, digits, `-` or `_`"
92        );
93        assert!(
94            !self.lists.contains_key(&key),
95            "the mailing list `{key}` is declared twice"
96        );
97        self.lists.insert(key.clone(), list.into_config(key));
98        self
99    }
100}
101
102impl MailingListServiceProvider {
103    /// Sends the confirmation email from laravel-template-engine whenever an active
104    /// `mailing-list.confirm` template exists, in the subscriber's language. Register
105    /// `TemplateEngineServiceProvider` too.
106    #[cfg(feature = "template-engine")]
107    #[must_use]
108    pub fn with_template_engine(mut self) -> Self {
109        self.template_engine = true;
110        self
111    }
112}
113
114/// Whether the application asked for the template engine with `with_template_engine`.
115#[cfg(feature = "template-engine")]
116#[derive(Clone, Copy, Debug, Default)]
117pub(crate) struct UseTemplateEngine(pub(crate) bool);
118
119laravel::db::migrations!(fn migrations = "database/migrations");
120
121impl ServiceProvider for MailingListServiceProvider {
122    fn config(&self, config: &mut Config, env: &Env) {
123        config.discover(env!("CARGO_CRATE_NAME"), env);
124    }
125
126    fn register(&self, app: &mut Registrar) {
127        app.discover(env!("CARGO_CRATE_NAME"));
128        app.migrations().add(migrations());
129        app.views()
130            .namespace("mailing-list", laravel::embed!("resources/views"));
131        app.instance(Lists(Arc::new(self.lists.clone())));
132        #[cfg(feature = "template-engine")]
133        app.instance(UseTemplateEngine(self.template_engine));
134        let config = app.config().section::<MailingListConfig>().clone();
135        app.routing().web(move |route| routes::register(route, &config));
136    }
137}