📝 Add mail and file upload guides
Document pagetop-mail (configuration, templates, layout, previews, queue and tests with the outbox) and file uploads (`web::Upload`, `form::File`, `web::Download` and the [upload] settings). doccheck enables the mail queue, keeps mail in memory and saves uploads under `target/`.
This commit is contained in:
parent
4e007feec8
commit
f42f5e9b89
13 changed files with 1118 additions and 8 deletions
11
README.md
11
README.md
|
|
@ -95,12 +95,13 @@ When writing a chapter:
|
||||||
```` ```rust,no_run ```` for the rest, and ```` ```rust,ignore ```` only for loose fragments
|
```` ```rust,no_run ```` for the rest, and ```` ```rust,ignore ```` only for loose fragments
|
||||||
that are not valid on their own.
|
that are not valid on their own.
|
||||||
- Examples can use `pagetop`, `pagetop-admin`, `pagetop-bootsier`, `pagetop-cron`,
|
- Examples can use `pagetop`, `pagetop-admin`, `pagetop-bootsier`, `pagetop-cron`,
|
||||||
`pagetop-htmx`, `pagetop-mail`, `pagetop-seaorm` (with SQLite), `pagetop-user`, `pagetop-build`,
|
`pagetop-htmx`, `pagetop-mail` (with its `queue` feature), `pagetop-seaorm` (with SQLite),
|
||||||
`serde`, `thiserror`, `tokio` and `tower-http` (with the `compression-gzip`, `cors`, `limit` and
|
`pagetop-user`, `pagetop-build`, `serde`, `thiserror`, `tokio` and `tower-http` (with the
|
||||||
`timeout` features); the translations in `tools/doccheck/src/locale/` (`LOCALES_APP`), and a
|
`compression-gzip`, `cors`, `limit` and `timeout` features); the translations in
|
||||||
static files bundle named `app`. If a chapter needs anything else, add it to `tools/doccheck`.
|
`tools/doccheck/src/locale/` (`LOCALES_APP`), and a static files bundle named `app`. If a chapter needs anything else, add it to `tools/doccheck`.
|
||||||
- Examples and tests that start an application read `tools/doccheck/config/`: those with a database
|
- Examples and tests that start an application read `tools/doccheck/config/`: those with a database
|
||||||
get a new in-memory SQLite one on every run.
|
get a new in-memory SQLite one on every run, mail is kept in memory (`pagetop_mail::outbox`) and
|
||||||
|
uploaded files go to `tools/doccheck/target/doccheck-uploads`.
|
||||||
- Tests that share state (a static store, a database) run in the same process: write one test per
|
- Tests that share state (a static store, a database) run in the same process: write one test per
|
||||||
flow, so that their results do not depend on the order they run in.
|
flow, so that their results do not depend on the order they run in.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@
|
||||||
- [Maquetar con Flex y Grid](how-to/layout.md)
|
- [Maquetar con Flex y Grid](how-to/layout.md)
|
||||||
- [Añadir navegación](how-to/navigation.md)
|
- [Añadir navegación](how-to/navigation.md)
|
||||||
- [Crear y procesar formularios](how-to/forms.md)
|
- [Crear y procesar formularios](how-to/forms.md)
|
||||||
|
- [Subir y descargar archivos](how-to/uploads.md)
|
||||||
- [Mostrar tablas ordenables y paginadas](how-to/tables.md)
|
- [Mostrar tablas ordenables y paginadas](how-to/tables.md)
|
||||||
- [Interactividad con HTMX]()
|
- [Interactividad con HTMX]()
|
||||||
- [Añadir HTMX a una aplicación](how-to/htmx-setup.md)
|
- [Añadir HTMX a una aplicación](how-to/htmx-setup.md)
|
||||||
|
|
@ -41,6 +42,7 @@
|
||||||
- [Configurar la aplicación](how-to/configuration.md)
|
- [Configurar la aplicación](how-to/configuration.md)
|
||||||
- [Compartir un servicio entre rutas](how-to/services.md)
|
- [Compartir un servicio entre rutas](how-to/services.md)
|
||||||
- [Programar tareas periódicas](how-to/cron.md)
|
- [Programar tareas periódicas](how-to/cron.md)
|
||||||
|
- [Enviar correo electrónico](how-to/mail.md)
|
||||||
- [Añadir *middleware*](how-to/middleware.md)
|
- [Añadir *middleware*](how-to/middleware.md)
|
||||||
- [Traducir la aplicación](how-to/localization.md)
|
- [Traducir la aplicación](how-to/localization.md)
|
||||||
- [Servir recursos estáticos](how-to/assets.md)
|
- [Servir recursos estáticos](how-to/assets.md)
|
||||||
|
|
|
||||||
|
|
@ -106,7 +106,7 @@ Con las capas de `tower-http` en `configure_middleware()`. Ver [Añadir
|
||||||
|
|
||||||
Sí, con dos extensiones oficiales: `pagetop-cron` ejecuta trabajos en segundo plano según una
|
Sí, con dos extensiones oficiales: `pagetop-cron` ejecuta trabajos en segundo plano según una
|
||||||
expresión cron o a intervalos (ve [Programar tareas periódicas](how-to/cron.md)), y `pagetop-mail`
|
expresión cron o a intervalos (ve [Programar tareas periódicas](how-to/cron.md)), y `pagetop-mail`
|
||||||
envía correo (ve [Extensiones oficiales](reference/extensions.md#correo)), con una cola opcional
|
envía correo (ve [Enviar correo electrónico](how-to/mail.md)), con una cola opcional
|
||||||
que guarda los correos en la base de datos y reintenta los que fallan. Lo que todavía no tiene
|
que guarda los correos en la base de datos y reintenta los que fallan. Lo que todavía no tiene
|
||||||
PageTop es una cola de trabajos genérica que sobreviva a un reinicio, como las de Loco (ve la
|
PageTop es una cola de trabajos genérica que sobreviva a un reinicio, como las de Loco (ve la
|
||||||
[comparación con otros *frameworks*](explanation/comparison.md)).
|
[comparación con otros *frameworks*](explanation/comparison.md)).
|
||||||
|
|
|
||||||
|
|
@ -115,6 +115,9 @@ server {
|
||||||
|
|
||||||
# ssl_certificate ... ssl_certificate_key ...
|
# ssl_certificate ... ssl_certificate_key ...
|
||||||
|
|
||||||
|
# Allows uploads up to upload.max_request_size (nginx accepts 1 MiB by default).
|
||||||
|
client_max_body_size 32m;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://127.0.0.1:8080;
|
proxy_pass http://127.0.0.1:8080;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
|
|
|
||||||
578
doc/v0.6/es/src/how-to/mail.md
Normal file
578
doc/v0.6/es/src/how-to/mail.md
Normal file
|
|
@ -0,0 +1,578 @@
|
||||||
|
# Enviar correo electrónico
|
||||||
|
|
||||||
|
**Objetivo:** enviar correos desde la aplicación, en texto y HTML, con adjuntos, traducidos al
|
||||||
|
idioma de cada destinatario y con el mismo aspecto que los de las demás extensiones, sin enviar
|
||||||
|
nunca correo real por error mientras desarrollas.
|
||||||
|
|
||||||
|
Lo aporta la extensión `pagetop-mail`. La configuración decide **cómo** se entregan los correos
|
||||||
|
(servidor SMTP, *sendmail*, archivos, trazas o memoria), así que el código que los envía es el
|
||||||
|
mismo en desarrollo, en las pruebas y en producción.
|
||||||
|
|
||||||
|
## 1. Añade la dependencia
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
pagetop-mail = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Y declara `pagetop_mail::Mail` en `dependencies()` de la extensión que envía correos:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
pub struct Garden;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Garden {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. Configura el envío
|
||||||
|
|
||||||
|
Sin configurar nada, los correos **no se envían**: se escriben en las trazas, con el remitente, los
|
||||||
|
destinatarios, el asunto y el texto. Es lo que quieres mientras desarrollas. Para enviarlos de
|
||||||
|
verdad, configura la sección `[mail]` con el transporte, el remitente y la URL pública de la
|
||||||
|
aplicación, que forma los enlaces de los correos (ver el paso 5):
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# config/production.toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
from = "Community garden <no-reply@example.com>"
|
||||||
|
base_url = "https://garden.example.com"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "smtp.example.com"
|
||||||
|
username = "no-reply@example.com"
|
||||||
|
```
|
||||||
|
|
||||||
|
La contraseña no va en un archivo versionado: ponla en `config/local.toml` o en la variable de
|
||||||
|
entorno `PAGETOP_MAIL__SMTP__PASSWORD`. Por defecto la conexión exige `STARTTLS` en el puerto 587;
|
||||||
|
`security = "tls"` usa el 465.
|
||||||
|
|
||||||
|
Para ver los correos tal como llegan sin enviarlos a nadie, usa en desarrollo un servidor como
|
||||||
|
[Mailpit](https://mailpit.axllent.org), que los recoge y los muestra en el navegador:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# config/local.toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "localhost"
|
||||||
|
port = 1025
|
||||||
|
security = "none"
|
||||||
|
```
|
||||||
|
|
||||||
|
Con `transport = "file"`, cada correo se guarda como un archivo `.eml` en el directorio `mail/`,
|
||||||
|
que abre cualquier cliente de correo. Y en un entorno de pruebas con datos reales,
|
||||||
|
`redirect_to = "qa@example.com"` entrega todos los correos sólo a esa dirección. Los ajustes no
|
||||||
|
válidos detienen el arranque con un mensaje que indica el problema.
|
||||||
|
|
||||||
|
## 3. Envía un correo
|
||||||
|
|
||||||
|
Un correo se compone con `Email`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
async fn confirm_plot(address: String) -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to(address)
|
||||||
|
.with_subject("Your plot is booked")
|
||||||
|
.with_html(html! {
|
||||||
|
p { "Your plot " strong { "B-12" } " is booked for the whole season." }
|
||||||
|
})
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Las direcciones admiten la forma `"Ana Pérez <ana@example.com>"`, y `with_cc()`, `with_bcc()` y
|
||||||
|
`with_reply_to()` completan los destinatarios; el remitente es el de `mail.from` salvo que indiques
|
||||||
|
otro con `with_from()`. Si el correo sólo tiene HTML, al enviarlo se genera su versión en texto
|
||||||
|
plano; escríbela tú con `with_text()` sólo si la generada no queda bien.
|
||||||
|
|
||||||
|
Hay dos formas de enviarlo:
|
||||||
|
|
||||||
|
- **`send().await`** espera a que el correo se entregue y devuelve el error si falla. Úsalo cuando
|
||||||
|
necesitas saberlo para responder.
|
||||||
|
- **`send_later()`** lo entrega en segundo plano y vuelve enseguida; si falla, lo registra en las
|
||||||
|
trazas. Es lo indicado en una petición del usuario: la respuesta no espera al servidor de
|
||||||
|
correo, y su tiempo no revela nada (por ejemplo, si existe la cuenta para la que se pide
|
||||||
|
recuperar la contraseña).
|
||||||
|
|
||||||
|
## 4. Escribe una plantilla traducida
|
||||||
|
|
||||||
|
Para que el mismo correo llegue a cada destinatario en su idioma, defínelo como un tipo que
|
||||||
|
implementa `MailTemplate`. Sus métodos reciben un `Context` con el idioma del destinatario, y los
|
||||||
|
textos se escriben con `Lc`, igual que en un componente:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
include_locales!(LOCALES_APP);
|
||||||
|
|
||||||
|
struct HarvestNotice {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailTemplate for HarvestNotice {
|
||||||
|
fn subject(&self, cx: &Context) -> String {
|
||||||
|
Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
||||||
|
Some(html! {
|
||||||
|
p { (greeting.using(cx)) }
|
||||||
|
p { (Lc::t("harvest-ready", &LOCALES_APP).using(cx)) }
|
||||||
|
p {
|
||||||
|
a href=(absolute_url("/harvest")) {
|
||||||
|
(Lc::t("harvest-link", &LOCALES_APP).using(cx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Con sus traducciones en `src/locale/en-US/app.ftl`:
|
||||||
|
|
||||||
|
```ftl
|
||||||
|
harvest-subject = The tomatoes are ready to pick
|
||||||
|
harvest-greeting = Hello, { $name }:
|
||||||
|
harvest-ready = The tomatoes in the community garden are ripe. Come and pick your share this week.
|
||||||
|
harvest-link = See the harvest calendar
|
||||||
|
```
|
||||||
|
|
||||||
|
`Email::from_template()` crea el correo con el asunto y el contenido de la plantilla. El contexto
|
||||||
|
decide el idioma. Si el destinatario es quien hace la petición (por ejemplo, al apuntarse a un
|
||||||
|
aviso), usa el de la petición. Si es otra persona, crea uno con su idioma, guardado junto a su
|
||||||
|
dirección; si no es un idioma disponible, el correo sale en el idioma por defecto de la aplicación:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
# struct HarvestNotice { name: String }
|
||||||
|
# impl MailTemplate for HarvestNotice {
|
||||||
|
# fn subject(&self, _cx: &Context) -> String { String::new() }
|
||||||
|
# }
|
||||||
|
async fn notify_gardener(name: String, email: String, language: String) -> Result<(), MailError> {
|
||||||
|
let cx = Context::default().with_langid(&Locale::resolve(language));
|
||||||
|
Email::from_template(&HarvestNotice { name }, &cx)
|
||||||
|
.with_to(email)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Usa enlaces absolutos
|
||||||
|
|
||||||
|
Un enlace de un correo se abre fuera de la aplicación, así que debe ser absoluto. `absolute_url()`
|
||||||
|
antepone a la ruta la URL pública de `mail.base_url`, como en la plantilla anterior. Si no la
|
||||||
|
configuras, usa la dirección y el puerto de escucha (`http://localhost:8080`), que sólo sirve en
|
||||||
|
desarrollo.
|
||||||
|
|
||||||
|
La URL no se deduce de la petición: la cabecera `Host` la elige el cliente, y un atacante podría
|
||||||
|
conseguir que el enlace de un correo de recuperación de contraseña apuntara a su propio servidor.
|
||||||
|
|
||||||
|
## 6. Adjunta archivos
|
||||||
|
|
||||||
|
`Attachment` crea un adjunto con un contenido en memoria o leyendo un archivo, y deduce su tipo del
|
||||||
|
nombre. Con `with_content_id()` el adjunto se incrusta en el HTML, que lo muestra con `cid:`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
async fn send_report(address: String, logo_png: Vec<u8>) -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to(address)
|
||||||
|
.with_subject("October harvest report")
|
||||||
|
.with_html(html! {
|
||||||
|
img src="cid:logo" alt="Community garden";
|
||||||
|
p { "The report of the month is attached." }
|
||||||
|
})
|
||||||
|
.with_attachment(Attachment::new("logo.png", logo_png).with_content_id("logo"))
|
||||||
|
.with_attachment(Attachment::from_path("reports/october.pdf").await?)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 7. Dale tu imagen a los correos
|
||||||
|
|
||||||
|
El HTML de un correo es sólo su contenido: al enviarlo se envuelve en un diseño común, sobrio y
|
||||||
|
neutro, con el nombre de la aplicación al pie. Para dar tu propia imagen a **todos** los correos,
|
||||||
|
también a los que envían otras extensiones como `pagetop-user`, registra la acción
|
||||||
|
`RenderMailLayout`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
fn garden_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
||||||
|
html! {
|
||||||
|
(DOCTYPE)
|
||||||
|
html lang=(cx.langid().to_string()) {
|
||||||
|
head {
|
||||||
|
meta charset="utf-8";
|
||||||
|
title { (email.subject()) }
|
||||||
|
}
|
||||||
|
body style="margin: 0; padding: 24px; background: #f0f5ec; font-family: sans-serif;" {
|
||||||
|
div style="max-width: 600px; margin: 0 auto; padding: 24px; background: #fff;" {
|
||||||
|
(content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Garden;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Garden {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![RenderMailLayout::new(garden_layout)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Si varias extensiones registran esta acción, se aplica sólo la de menor peso
|
||||||
|
(`RenderMailLayout::new(..).with_weight(..)`). Los clientes de correo ignoran las hojas de estilo
|
||||||
|
externas, y muchos también los estilos del `<head>`: escribe los estilos en línea, con `style`. Un
|
||||||
|
correo concreto puede saltarse el diseño con `with_html_document()`, que envía el documento tal
|
||||||
|
cual.
|
||||||
|
|
||||||
|
## 8. Revisa los correos en el navegador
|
||||||
|
|
||||||
|
Para ver cómo queda un correo sin enviarlo, declara una vista previa con datos de ejemplo:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
# struct HarvestNotice { name: String }
|
||||||
|
# impl MailTemplate for HarvestNotice {
|
||||||
|
# fn subject(&self, _cx: &Context) -> String { String::new() }
|
||||||
|
# }
|
||||||
|
fn harvest_preview(cx: &Context) -> Email {
|
||||||
|
let notice = HarvestNotice { name: "Ana".to_string() };
|
||||||
|
Email::from_template(¬ice, cx).with_to("ana@example.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declare_previews(previews: &mut MailPreviews) {
|
||||||
|
previews.add("garden.harvest", Lc::n("Harvest notice"), harvest_preview);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Garden;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Garden {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![DeclareMailPreviews::new(declare_previews)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Activa las vistas previas sólo en desarrollo, porque muestran las plantillas a quien conozca la
|
||||||
|
ruta:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# config/local.toml
|
||||||
|
[mail]
|
||||||
|
previews = true
|
||||||
|
```
|
||||||
|
|
||||||
|
`/mail/preview` lista los correos declarados por todas las extensiones, y cada uno se muestra
|
||||||
|
completo, con el diseño común, las cabeceras, el texto plano y los adjuntos. Añade `?lang=es` para
|
||||||
|
verlo en otro idioma.
|
||||||
|
|
||||||
|
## 9. Guarda los correos en una cola
|
||||||
|
|
||||||
|
Sin más, un correo de `send_later()` se pierde si la aplicación se detiene antes de entregarlo, y
|
||||||
|
no se reintenta si el servidor falla. Con la *feature* `queue`, los correos se guardan en la base
|
||||||
|
de datos de `pagetop-seaorm` y se reintentan:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
pagetop-mail = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["queue"] }
|
||||||
|
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||||
|
```
|
||||||
|
|
||||||
|
La cola crea su tabla al arrancar, en la base de datos de `[database]`. Con ella:
|
||||||
|
|
||||||
|
- **`send_later()`** guarda el correo y lo intenta enseguida (salvo con `transport = "log"`, que
|
||||||
|
lo escribe directamente en las trazas). Si el fallo es temporal, queda en la cola y se reintenta
|
||||||
|
más tarde, también después de un reinicio, con una espera que se duplica en cada intento. Un
|
||||||
|
rechazo definitivo del servidor o el último intento lo dejan como fallido.
|
||||||
|
- **`queue()`** sólo lo guarda: el trabajo `mail.queue` de `pagetop-cron` envía los pendientes por
|
||||||
|
lotes, uno tras otro. Es lo indicado para los envíos masivos, que así no saturan el equipo ni el
|
||||||
|
servidor de correo:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
async fn announce_closure(addresses: Vec<String>) -> Result<(), MailError> {
|
||||||
|
for address in addresses {
|
||||||
|
Email::new()
|
||||||
|
.with_to(address)
|
||||||
|
.with_subject("The garden closes on Saturday")
|
||||||
|
.with_text("The garden will be closed on Saturday for the water works.")
|
||||||
|
.queue()
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
El tamaño de los lotes y los reintentos se ajustan en
|
||||||
|
[`[mail.queue]`](../reference/configuration.md#mailqueue), y el ritmo en la programación del
|
||||||
|
trabajo:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[cron.jobs."mail.queue"]
|
||||||
|
schedule = "@delay 30s" # 30 s after each batch ends (1 minute by default).
|
||||||
|
```
|
||||||
|
|
||||||
|
La cola guarda los mensajes completos y sin cifrar hasta entregarlos: pueden contener datos
|
||||||
|
personales y enlaces de un solo uso, también en las copias de seguridad de la base de datos.
|
||||||
|
|
||||||
|
## El ejemplo completo
|
||||||
|
|
||||||
|
Un formulario en `/harvest` donde cada visitante pide el aviso de la cosecha, que recibe por
|
||||||
|
correo en su idioma:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
include_locales!(LOCALES_APP);
|
||||||
|
|
||||||
|
struct HarvestNotice {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailTemplate for HarvestNotice {
|
||||||
|
fn subject(&self, cx: &Context) -> String {
|
||||||
|
Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
||||||
|
Some(html! {
|
||||||
|
p { (greeting.using(cx)) }
|
||||||
|
p { (Lc::t("harvest-ready", &LOCALES_APP).using(cx)) }
|
||||||
|
p {
|
||||||
|
a href=(absolute_url("/harvest")) {
|
||||||
|
(Lc::t("harvest-link", &LOCALES_APP).using(cx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn harvest_preview(cx: &Context) -> Email {
|
||||||
|
let notice = HarvestNotice { name: "Ana".to_string() };
|
||||||
|
Email::from_template(¬ice, cx).with_to("ana@example.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declare_previews(previews: &mut MailPreviews) {
|
||||||
|
previews.add("garden.harvest", Lc::n("Harvest notice"), harvest_preview);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Garden;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Garden {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![DeclareMailPreviews::new(declare_previews)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
|
router.route("/harvest", web::get(show).post(notify))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Gardener {
|
||||||
|
name: String,
|
||||||
|
email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notice_form() -> Form {
|
||||||
|
Form::new()
|
||||||
|
.with_action("/harvest")
|
||||||
|
.with_method(form::Method::Post)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("name")
|
||||||
|
.with_label(Lc::n("Name"))
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::email()
|
||||||
|
.with_name("email")
|
||||||
|
.with_label(Lc::n("Email"))
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(Button::submit(Lc::n("Send me the notice")))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
Page::new(request)
|
||||||
|
.with_title(Lc::n("Harvest"))
|
||||||
|
.with_child(notice_form())
|
||||||
|
.render()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn notify(
|
||||||
|
request: HttpRequest,
|
||||||
|
web::Form(gardener): web::Form<Gardener>,
|
||||||
|
) -> Result<Response, ErrorPage> {
|
||||||
|
// The notice goes in the language of the visitor who asks for it.
|
||||||
|
let cx = Context::new(request.clone());
|
||||||
|
let notice = HarvestNotice { name: gardener.name };
|
||||||
|
let sent = Email::from_template(¬ice, &cx)
|
||||||
|
.with_to(gardener.email)
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
if let Err(err) = sent {
|
||||||
|
trace::warn!("Harvest notice not sent: {err}");
|
||||||
|
let mut page = Page::new(request)
|
||||||
|
.with_title(Lc::n("Harvest"))
|
||||||
|
.with_child(notice_form());
|
||||||
|
page.context().push_message(
|
||||||
|
MessageLevel::Error,
|
||||||
|
Lc::n("The notice could not be sent. Check the address and try again."),
|
||||||
|
);
|
||||||
|
return page.render().await.map(IntoResponse::into_response);
|
||||||
|
}
|
||||||
|
Ok(Redirect::see_other(cx.route("/harvest")).with_message(
|
||||||
|
&cx,
|
||||||
|
MessageLevel::Info,
|
||||||
|
Lc::n("We have sent you the notice. Check your inbox."),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
Application::prepare(&Garden).await.run().await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
El ejemplo usa `send().await` para avisar en el formulario si la dirección no es válida o el
|
||||||
|
servidor la rechaza. Si prefieres no hacer esperar al visitante, cambia `send().await` por
|
||||||
|
`send_later()` y avisa siempre del envío: los fallos quedarán en las trazas.
|
||||||
|
|
||||||
|
## Comprueba
|
||||||
|
|
||||||
|
Arranca con `cargo run`, abre <http://localhost:8080/harvest> y envía el formulario: la página
|
||||||
|
confirma el envío y el terminal muestra el correo, porque sin configurar `[mail]` se escribe en las
|
||||||
|
trazas. Con `previews = true` en `config/local.toml`, <http://localhost:8080/mail/preview> lo
|
||||||
|
muestra con su diseño.
|
||||||
|
|
||||||
|
En las pruebas, el transporte `memory` guarda los correos en lugar de enviarlos, y
|
||||||
|
`pagetop_mail::outbox` los recoge. Configúralo en `config/test.toml` (ve [Usa otra configuración
|
||||||
|
para las pruebas](testing.md#5-usa-otra-configuración-para-las-pruebas)):
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# config/test.toml
|
||||||
|
[mail]
|
||||||
|
transport = "memory"
|
||||||
|
from = "Community garden <garden@example.com>"
|
||||||
|
base_url = "https://garden.example.com"
|
||||||
|
```
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
# use serde::Deserialize;
|
||||||
|
# include_locales!(LOCALES_APP);
|
||||||
|
# struct HarvestNotice { name: String }
|
||||||
|
# impl MailTemplate for HarvestNotice {
|
||||||
|
# fn subject(&self, cx: &Context) -> String {
|
||||||
|
# Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
||||||
|
# }
|
||||||
|
# fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
# let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
||||||
|
# let link = Lc::t("harvest-link", &LOCALES_APP);
|
||||||
|
# Some(html! {
|
||||||
|
# p { (greeting.using(cx)) }
|
||||||
|
# p { a href=(absolute_url("/harvest")) { (link.using(cx)) } }
|
||||||
|
# })
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# struct Garden;
|
||||||
|
# #[async_trait]
|
||||||
|
# impl Extension for Garden {
|
||||||
|
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
# vec![&pagetop_mail::Mail]
|
||||||
|
# }
|
||||||
|
# fn configure_router(&self, router: Router) -> Router {
|
||||||
|
# router.route("/harvest", web::post(notify))
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# #[derive(Deserialize)]
|
||||||
|
# struct Gardener { name: String, email: String }
|
||||||
|
# async fn notify(
|
||||||
|
# request: HttpRequest,
|
||||||
|
# web::Form(gardener): web::Form<Gardener>,
|
||||||
|
# ) -> Result<Response, ErrorPage> {
|
||||||
|
# let cx = Context::new(request.clone());
|
||||||
|
# Email::from_template(&HarvestNotice { name: gardener.name }, &cx)
|
||||||
|
# .with_to(gardener.email)
|
||||||
|
# .send()
|
||||||
|
# .await
|
||||||
|
# .map_err(|_| ErrorPage::InternalError(Some(request)))?;
|
||||||
|
# Ok(Redirect::see_other(cx.route("/harvest")))
|
||||||
|
# }
|
||||||
|
use pagetop_mail::outbox;
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn sends_the_harvest_notice() {
|
||||||
|
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
||||||
|
|
||||||
|
let request = web::test::TestRequest::post()
|
||||||
|
.uri("/harvest")
|
||||||
|
.form("name=Ana&email=ana%40example.com")
|
||||||
|
.to_request();
|
||||||
|
let response = web::test::send_request(&app, request).await;
|
||||||
|
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
||||||
|
|
||||||
|
let sent = outbox::take_to("ana@example.com");
|
||||||
|
assert_eq!(sent.len(), 1);
|
||||||
|
assert_eq!(sent[0].email().subject(), "The tomatoes are ready to pick");
|
||||||
|
assert!(sent[0].links().contains(&"https://garden.example.com/harvest".to_string()));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`take_to()` recoge sólo los correos de esa dirección, así que las pruebas que se ejecutan en
|
||||||
|
paralelo no se roban los correos. `links()` devuelve las direcciones de los enlaces del HTML, para
|
||||||
|
seguir en la prueba, por ejemplo, un enlace de un solo uso.
|
||||||
|
|
||||||
|
Si el correo sale con `send_later()`, llega a `outbox` en segundo plano, poco después de la
|
||||||
|
respuesta. Con la *feature* `queue`, los de `queue()` sólo llegan cuando se ejecuta el trabajo, que
|
||||||
|
en las pruebas se lanza con `pagetop_cron::run_now("mail.queue")`.
|
||||||
|
|
||||||
|
## Siguiente
|
||||||
|
|
||||||
|
- [Opciones de configuración](../reference/configuration.md#mail): todas las claves de `[mail]`.
|
||||||
|
- [Programar tareas periódicas](cron.md): el planificador que vacía la cola.
|
||||||
|
- [Añadir usuarios y permisos](users.md): `pagetop-user` envía con esta extensión sus correos de
|
||||||
|
recuperación de contraseña y de verificación.
|
||||||
486
doc/v0.6/es/src/how-to/uploads.md
Normal file
486
doc/v0.6/es/src/how-to/uploads.md
Normal file
|
|
@ -0,0 +1,486 @@
|
||||||
|
# Subir y descargar archivos
|
||||||
|
|
||||||
|
**Objetivo:** recibir archivos desde un formulario, guardarlos en el servidor con límites de tamaño
|
||||||
|
y de tipo, y servirlos después sólo a quien pueda verlos.
|
||||||
|
|
||||||
|
Todo lo necesario está en el núcleo de PageTop: el campo `form::File`, `web::Upload` para recibir
|
||||||
|
y guardar los archivos, y `web::Download` para servirlos.
|
||||||
|
|
||||||
|
## 1. Define la subida
|
||||||
|
|
||||||
|
`web::Upload` describe qué se admite y dónde se guarda. Defínelo una sola vez, en una función, para
|
||||||
|
que el formulario y el servidor compartan las mismas reglas:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
fn photo_upload() -> web::Upload {
|
||||||
|
web::Upload::new()
|
||||||
|
.with_subdir("photos")
|
||||||
|
.with_extensions(["jpg", "jpeg", "png"])
|
||||||
|
.with_file_fields(["photo"])
|
||||||
|
.with_max_size(2 * 1024 * 1024)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Método | Para qué |
|
||||||
|
|---|---|
|
||||||
|
| `with_subdir("photos")` | Subdirectorio, dentro del de archivos subidos (`[upload] dir`) |
|
||||||
|
| `with_extensions(["jpg", "png"])` | Extensiones admitidas; un archivo con otra se rechaza |
|
||||||
|
| `with_file_fields(["photo"])` | Campos del formulario que pueden traer archivos; uno en otro campo se rechaza |
|
||||||
|
| `with_max_size(bytes)` | Tamaño máximo de cada archivo, en lugar del de la configuración |
|
||||||
|
| `with_max_files(n)` | Número máximo de archivos de un envío, en lugar del de la configuración |
|
||||||
|
|
||||||
|
Restringe siempre las extensiones: es la defensa más sencilla contra quien sube una página HTML o un
|
||||||
|
programa en lugar de una foto.
|
||||||
|
|
||||||
|
## 2. Construye el formulario
|
||||||
|
|
||||||
|
Un formulario con archivos necesita la codificación `multipart/form-data`, que se indica con
|
||||||
|
`form::Enctype::Multipart`. El campo es `form::File`, y con `accept()` ofrece al usuario los mismos
|
||||||
|
tipos que admite el servidor:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# fn photo_upload() -> web::Upload { web::Upload::new() }
|
||||||
|
fn photo_form() -> Form {
|
||||||
|
Form::new()
|
||||||
|
.with_action("/photos")
|
||||||
|
.with_method(form::Method::Post)
|
||||||
|
.with_enctype(form::Enctype::Multipart)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("title")
|
||||||
|
.with_label(Lc::n("Title"))
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::File::new()
|
||||||
|
.with_name("photo")
|
||||||
|
.with_label(Lc::n("Photo"))
|
||||||
|
.with_accept(photo_upload().accept())
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(Button::submit(Lc::n("Upload")))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Para elegir varios archivos en el mismo campo, añade `with_multiple(true)`.
|
||||||
|
|
||||||
|
## 3. Recibe el envío
|
||||||
|
|
||||||
|
El *handler* recibe el cuerpo con el extractor `web::Multipart`, siempre como **último** parámetro.
|
||||||
|
`receive()` guarda los archivos según las reglas del paso 1 y deserializa los campos de texto en una
|
||||||
|
estructura, como hace `web::Form` en un formulario sin archivos:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# fn photo_upload() -> web::Upload { web::Upload::new() }
|
||||||
|
# async fn show_form(_request: HttpRequest, _error: Lc) -> Result<Response, ErrorPage> { todo!() }
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct PhotoData {
|
||||||
|
title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
||||||
|
let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
||||||
|
Ok(sent) => sent,
|
||||||
|
// Too large, a type not allowed...: shows the form again with the reason.
|
||||||
|
Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
||||||
|
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||||
|
};
|
||||||
|
let Some(photo) = sent.file("photo") else {
|
||||||
|
return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
||||||
|
};
|
||||||
|
// Save `sent.form().title`, `photo.path()` and `photo.original_name()`, for example in the
|
||||||
|
// database. If anything fails before `keep()`, the file is deleted.
|
||||||
|
sent.keep();
|
||||||
|
let cx = Context::new(request);
|
||||||
|
Ok(Redirect::see_other(cx.route("/photos")).with_message(
|
||||||
|
&cx,
|
||||||
|
MessageLevel::Info,
|
||||||
|
Lc::n("Photo uploaded."),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Fíjate en tres cosas:
|
||||||
|
|
||||||
|
- **Los errores del usuario se distinguen de los del servidor.** `is_client_error()` es cierto si
|
||||||
|
el archivo es demasiado grande, de un tipo no admitido o el envío está mal formado, y
|
||||||
|
`message()` explica el motivo, ya traducido, con el nombre del archivo y el límite superado.
|
||||||
|
- **Los archivos se borran si no llamas a `keep()`.** El envío recibido conserva sus archivos sólo
|
||||||
|
si llegas a `keep()`, cuando ya está todo guardado. Si la validación o la base de datos fallan y
|
||||||
|
sales antes, con `return` o con `?`, no quedan archivos huérfanos en el disco.
|
||||||
|
- **El nombre que envía el navegador nunca llega al disco.** Cada archivo se guarda con un nombre
|
||||||
|
aleatorio y la extensión del original, y `path()` devuelve su ruta relativa
|
||||||
|
(`photos/3f9c2a7d1b4e8a60.jpg`): es lo que se guarda en la base de datos. El nombre original,
|
||||||
|
saneado, queda en `original_name()`, sólo para mostrarlo.
|
||||||
|
|
||||||
|
`content_type()` devuelve el tipo que declara el navegador, pero no se comprueba contra el
|
||||||
|
contenido: no lo tomes como garantía de que el archivo es lo que dice.
|
||||||
|
|
||||||
|
## 4. Sirve el archivo con permisos
|
||||||
|
|
||||||
|
Los archivos subidos no se publican como estáticos. Se sirven desde un *handler*, que antes
|
||||||
|
comprueba si quien los pide puede verlos y busca su ruta, con `web::Download`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# fn find_photo(_index: usize) -> Option<(String, String)> { None }
|
||||||
|
async fn photo(
|
||||||
|
request: HttpRequest,
|
||||||
|
web::Path(index): web::Path<usize>,
|
||||||
|
) -> Result<Response, ErrorPage> {
|
||||||
|
// Check the permissions here, as in any other handler...
|
||||||
|
let Some((path, original_name)) = find_photo(index) else {
|
||||||
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
};
|
||||||
|
web::Download::new(path)
|
||||||
|
.with_file_name(original_name)
|
||||||
|
.serve(&request)
|
||||||
|
.await
|
||||||
|
.map_err(|err| match err {
|
||||||
|
web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
|
||||||
|
_ => ErrorPage::InternalError(Some(request)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`Download` envía el tipo que corresponde a la extensión del archivo guardado, y el nombre original
|
||||||
|
para guardarlo. Las imágenes (salvo SVG), el audio, el vídeo, los PDF y el texto plano se muestran
|
||||||
|
en el navegador; el resto se descarga, para que un `.html` o un `.svg` subido no se ejecute como una
|
||||||
|
página más de tu sitio. `with_attachment(true)` obliga a descargar también los primeros. Atiende
|
||||||
|
las descargas parciales (para reanudar o avanzar en un vídeo), y el navegador vuelve a preguntar
|
||||||
|
antes de reutilizar el archivo, así que cada visita pasa por tu *handler* y sus permisos.
|
||||||
|
|
||||||
|
La ruta debe salir de tu aplicación (la que guardaste en la base de datos), nunca directamente de la
|
||||||
|
petición: aunque `Download` no sale del directorio de archivos subidos, daría acceso a cualquiera de
|
||||||
|
ellos.
|
||||||
|
|
||||||
|
## 5. Borra los archivos que ya no se usan
|
||||||
|
|
||||||
|
Al borrar o sustituir el registro que apunta a un archivo, borra también el archivo:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
async fn delete_photo_file(path: &str) -> Result<(), web::UploadError> {
|
||||||
|
web::Upload::remove(path).await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
No es un error que el archivo ya no exista, y una ruta que intente salir del directorio de
|
||||||
|
archivos subidos (con `..`, por ejemplo) se rechaza.
|
||||||
|
|
||||||
|
## 6. Ajusta los límites
|
||||||
|
|
||||||
|
Los valores por defecto sirven para la mayoría de las aplicaciones:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[upload]
|
||||||
|
dir = "uploads" # Where files are saved (relative to the working directory).
|
||||||
|
max_file_size = 8388608 # 8 MiB per file (0 = only max_request_size).
|
||||||
|
max_files = 20 # Files per submission (0 = no limit).
|
||||||
|
max_request_size = 33554432 # 32 MiB for a whole multipart/form-data request (0 = no limit).
|
||||||
|
```
|
||||||
|
|
||||||
|
Las peticiones `multipart/form-data` pueden llegar a `max_request_size`, porque sus archivos se
|
||||||
|
escriben en disco según llegan. El resto de cuerpos (`web::Form`, JSON) se leen enteros en memoria
|
||||||
|
y se limitan con `max_body_size` de `[server]` (2 MiB): uno mayor se rechaza con `413`. Ese límite
|
||||||
|
acota también la suma de los campos de texto de un formulario con archivos.
|
||||||
|
|
||||||
|
Un envío con archivos que supera cualquiera de estos límites llega a `receive()` como un error del
|
||||||
|
usuario, así que el formulario vuelve con el motivo («El envío supera el tamaño máximo de 32 MiB»,
|
||||||
|
por ejemplo) en lugar de mostrar una página de error.
|
||||||
|
|
||||||
|
En producción, el directorio `dir` debe sobrevivir a los despliegues: fuera del directorio de la
|
||||||
|
aplicación, o en un volumen si usas contenedores. Y si un proxy inverso va delante, su límite de
|
||||||
|
tamaño también debe admitir los envíos: nginx rechaza por defecto los cuerpos de más de 1 MiB, así
|
||||||
|
que añade `client_max_body_size 32m;` a su configuración (ve [Detrás de un proxy
|
||||||
|
inverso](deployment.md#5-detrás-de-un-proxy-inverso)).
|
||||||
|
|
||||||
|
## 7. Con HTMX
|
||||||
|
|
||||||
|
Un formulario con `form::Enctype::Multipart` se envía igual con HTMX: HTMX respeta su `enctype`.
|
||||||
|
Sólo si la petición sale de otro elemento que no es el formulario, indícalo con el atributo
|
||||||
|
`hx::ENCODING` de `pagetop-htmx` y el valor `"multipart/form-data"`.
|
||||||
|
|
||||||
|
## El ejemplo completo
|
||||||
|
|
||||||
|
Un tablón de fotos del huerto: el formulario sube una foto con su título, y la lista enlaza cada
|
||||||
|
una, servida por su *handler*. Las fotos se guardan en memoria para no depender de una base de
|
||||||
|
datos:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use std::sync::{Mutex, MutexGuard};
|
||||||
|
|
||||||
|
struct Photo {
|
||||||
|
title: String,
|
||||||
|
path: String,
|
||||||
|
original_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
static PHOTOS: Mutex<Vec<Photo>> = Mutex::new(Vec::new());
|
||||||
|
|
||||||
|
fn photos() -> MutexGuard<'static, Vec<Photo>> {
|
||||||
|
PHOTOS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn photo_upload() -> web::Upload {
|
||||||
|
web::Upload::new()
|
||||||
|
.with_subdir("photos")
|
||||||
|
.with_extensions(["jpg", "jpeg", "png"])
|
||||||
|
.with_file_fields(["photo"])
|
||||||
|
.with_max_size(2 * 1024 * 1024)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Garden;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Garden {
|
||||||
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
|
router
|
||||||
|
.route("/photos", web::get(gallery).post(upload))
|
||||||
|
.route("/photos/{index}", web::get(photo))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn photo_form() -> Form {
|
||||||
|
Form::new()
|
||||||
|
.with_action("/photos")
|
||||||
|
.with_method(form::Method::Post)
|
||||||
|
.with_enctype(form::Enctype::Multipart)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("title")
|
||||||
|
.with_label(Lc::n("Title"))
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::File::new()
|
||||||
|
.with_name("photo")
|
||||||
|
.with_label(Lc::n("Photo"))
|
||||||
|
.with_accept(photo_upload().accept())
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(Button::submit(Lc::n("Upload")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gallery_page(request: HttpRequest) -> Page {
|
||||||
|
let list = html! {
|
||||||
|
ul {
|
||||||
|
@for (index, photo) in photos().iter().enumerate() {
|
||||||
|
li { a href=(util::join!("/photos/", index.to_string())) { (photo.title) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Page::new(request)
|
||||||
|
.with_title(Lc::n("Garden photos"))
|
||||||
|
.with_child(photo_form())
|
||||||
|
.with_child(Html::with(move |_| list.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn gallery(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
gallery_page(request).render().await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show_form(request: HttpRequest, error: Lc) -> Result<Response, ErrorPage> {
|
||||||
|
let mut page = gallery_page(request);
|
||||||
|
page.context().push_message(MessageLevel::Error, error);
|
||||||
|
page.render().await.map(IntoResponse::into_response)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PhotoData {
|
||||||
|
title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
||||||
|
let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
||||||
|
Ok(sent) => sent,
|
||||||
|
Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
||||||
|
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||||
|
};
|
||||||
|
let Some(file) = sent.file("photo") else {
|
||||||
|
return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
||||||
|
};
|
||||||
|
let photo = Photo {
|
||||||
|
title: sent.form().title.clone(),
|
||||||
|
path: file.path().to_string(),
|
||||||
|
original_name: file.original_name().to_string(),
|
||||||
|
};
|
||||||
|
photos().push(photo);
|
||||||
|
sent.keep();
|
||||||
|
let cx = Context::new(request);
|
||||||
|
Ok(Redirect::see_other(cx.route("/photos")).with_message(
|
||||||
|
&cx,
|
||||||
|
MessageLevel::Info,
|
||||||
|
Lc::n("Photo uploaded."),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn photo(
|
||||||
|
request: HttpRequest,
|
||||||
|
web::Path(index): web::Path<usize>,
|
||||||
|
) -> Result<Response, ErrorPage> {
|
||||||
|
let found = photos()
|
||||||
|
.get(index)
|
||||||
|
.map(|photo| (photo.path.clone(), photo.original_name.clone()));
|
||||||
|
let Some((path, original_name)) = found else {
|
||||||
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
};
|
||||||
|
web::Download::new(path)
|
||||||
|
.with_file_name(original_name)
|
||||||
|
.serve(&request)
|
||||||
|
.await
|
||||||
|
.map_err(|err| match err {
|
||||||
|
web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
|
||||||
|
_ => ErrorPage::InternalError(Some(request)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
Application::prepare(&Garden).await.run().await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Comprueba
|
||||||
|
|
||||||
|
Arranca con `cargo run` y abre <http://localhost:8080/photos>:
|
||||||
|
|
||||||
|
1. Sube una foto `.jpg` o `.png` con un título: vuelves a la lista con el aviso «Photo uploaded.»,
|
||||||
|
y el archivo está en `uploads/photos/` con un nombre aleatorio.
|
||||||
|
2. Pulsa su enlace: el navegador muestra la foto.
|
||||||
|
3. Intenta subir otro tipo de archivo (el selector propone sólo fotos, pero la mayoría de los
|
||||||
|
navegadores permite elegir cualquier archivo): el formulario vuelve con el motivo del rechazo, y
|
||||||
|
no se guarda nada.
|
||||||
|
|
||||||
|
En las pruebas, un envío `multipart/form-data` se escribe a mano con `body()` y su cabecera
|
||||||
|
`Content-Type`. Para no llenar de archivos el directorio del proyecto, apunta `dir` de `[upload]` a
|
||||||
|
otro lugar en `config/test.toml` (por ejemplo, `"target/test-uploads"`):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use serde::Deserialize;
|
||||||
|
# use std::sync::{Mutex, MutexGuard};
|
||||||
|
# struct Photo { path: String, original_name: String }
|
||||||
|
# static PHOTOS: Mutex<Vec<Photo>> = Mutex::new(Vec::new());
|
||||||
|
# fn photos() -> MutexGuard<'static, Vec<Photo>> {
|
||||||
|
# PHOTOS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
# }
|
||||||
|
# fn photo_upload() -> web::Upload {
|
||||||
|
# web::Upload::new()
|
||||||
|
# .with_subdir("photos")
|
||||||
|
# .with_extensions(["jpg", "jpeg", "png"])
|
||||||
|
# .with_file_fields(["photo"])
|
||||||
|
# }
|
||||||
|
# struct Garden;
|
||||||
|
# #[async_trait]
|
||||||
|
# impl Extension for Garden {
|
||||||
|
# fn configure_router(&self, router: Router) -> Router {
|
||||||
|
# router
|
||||||
|
# .route("/photos", web::post(upload))
|
||||||
|
# .route("/photos/{index}", web::get(photo))
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# #[derive(Deserialize)]
|
||||||
|
# struct PhotoData {
|
||||||
|
# #[allow(dead_code)]
|
||||||
|
# title: String,
|
||||||
|
# }
|
||||||
|
# async fn show_form(request: HttpRequest, error: Lc) -> Result<Response, ErrorPage> {
|
||||||
|
# let mut page = Page::new(request);
|
||||||
|
# page.context().push_message(MessageLevel::Error, error);
|
||||||
|
# page.render().await.map(IntoResponse::into_response)
|
||||||
|
# }
|
||||||
|
# async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
||||||
|
# let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
||||||
|
# Ok(sent) => sent,
|
||||||
|
# Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
||||||
|
# Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||||
|
# };
|
||||||
|
# let Some(file) = sent.file("photo") else {
|
||||||
|
# return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
||||||
|
# };
|
||||||
|
# let photo = Photo {
|
||||||
|
# path: file.path().to_string(),
|
||||||
|
# original_name: file.original_name().to_string(),
|
||||||
|
# };
|
||||||
|
# photos().push(photo);
|
||||||
|
# sent.keep();
|
||||||
|
# Ok(Redirect::see_other("/photos"))
|
||||||
|
# }
|
||||||
|
# async fn photo(
|
||||||
|
# request: HttpRequest,
|
||||||
|
# web::Path(index): web::Path<usize>,
|
||||||
|
# ) -> Result<Response, ErrorPage> {
|
||||||
|
# let found = photos()
|
||||||
|
# .get(index)
|
||||||
|
# .map(|photo| (photo.path.clone(), photo.original_name.clone()));
|
||||||
|
# let Some((path, original_name)) = found else {
|
||||||
|
# return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
# };
|
||||||
|
# web::Download::new(path)
|
||||||
|
# .with_file_name(original_name)
|
||||||
|
# .serve(&request)
|
||||||
|
# .await
|
||||||
|
# .map_err(|_| ErrorPage::NotFound(Some(request)))
|
||||||
|
# }
|
||||||
|
// A submission with a title and one file, as a browser sends it.
|
||||||
|
fn photo_body(file_name: &str, content: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"--boundary\r\n\
|
||||||
|
Content-Disposition: form-data; name=\"title\"\r\n\r\n\
|
||||||
|
First tomatoes\r\n\
|
||||||
|
--boundary\r\n\
|
||||||
|
Content-Disposition: form-data; name=\"photo\"; filename=\"{file_name}\"\r\n\
|
||||||
|
Content-Type: application/octet-stream\r\n\r\n\
|
||||||
|
{content}\r\n\
|
||||||
|
--boundary--\r\n"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_photo(file_name: &str, content: &str) -> web::test::TestRequest {
|
||||||
|
web::test::TestRequest::post()
|
||||||
|
.uri("/photos")
|
||||||
|
.header("content-type", "multipart/form-data; boundary=boundary")
|
||||||
|
.body(photo_body(file_name, content))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn uploads_and_serves_a_photo() {
|
||||||
|
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
||||||
|
|
||||||
|
// A file of a type not allowed is rejected with the reason, and nothing is saved.
|
||||||
|
let request = send_photo("tomatoes.exe", "MZ").to_request();
|
||||||
|
let response = web::test::send_request(&app, request).await;
|
||||||
|
let body = web::test::read_body_text(response).await;
|
||||||
|
assert!(body.contains("is not an allowed file type"), "{body}");
|
||||||
|
assert!(photos().is_empty());
|
||||||
|
|
||||||
|
// A photo is saved under a random name and served with its original one.
|
||||||
|
let request = send_photo("tomatoes.png", "PNG data").to_request();
|
||||||
|
let response = web::test::send_request(&app, request).await;
|
||||||
|
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
||||||
|
let saved = photos()[0].path.clone();
|
||||||
|
assert!(saved.starts_with("photos/") && saved.ends_with(".png"), "{saved}");
|
||||||
|
|
||||||
|
let request = web::test::TestRequest::get().uri("/photos/0").to_request();
|
||||||
|
let response = web::test::send_request(&app, request).await;
|
||||||
|
assert_eq!(response.status(), web::http::StatusCode::OK);
|
||||||
|
assert_eq!(response.headers()["content-type"], "image/png");
|
||||||
|
assert_eq!(web::test::read_body_text(response).await, "PNG data");
|
||||||
|
|
||||||
|
web::Upload::remove(saved).await.unwrap();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Siguiente
|
||||||
|
|
||||||
|
- [Crear y procesar formularios](forms.md): campos, validación y avisos tras redirigir.
|
||||||
|
- [Opciones de configuración](../reference/configuration.md#upload): todas las claves de
|
||||||
|
`[upload]`.
|
||||||
|
- [Desplegar en producción](deployment.md): el proxy inverso delante de la aplicación.
|
||||||
|
|
@ -27,6 +27,8 @@ Lo esencial de PageTop en una página. Cada línea enlaza con la guía que lo ex
|
||||||
| [Un segmento de la URL](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Path(id): web::Path<u32>` |
|
| [Un segmento de la URL](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Path(id): web::Path<u32>` |
|
||||||
| [Parámetros de consulta](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Query(q): web::Query<T>` |
|
| [Parámetros de consulta](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Query(q): web::Query<T>` |
|
||||||
| [Un formulario](../how-to/forms.md#3-recibe-y-valida-los-datos) | `web::Form(data): web::Form<T>` (el último parámetro) |
|
| [Un formulario](../how-to/forms.md#3-recibe-y-valida-los-datos) | `web::Form(data): web::Form<T>` (el último parámetro) |
|
||||||
|
| [Un formulario con archivos](../how-to/uploads.md#3-recibe-el-envío) | `upload.receive::<T>(multipart).await` con `multipart: web::Multipart` (el último parámetro) |
|
||||||
|
| [Servir un archivo subido](../how-to/uploads.md#4-sirve-el-archivo-con-permisos) | `web::Download::new(path).with_file_name(name).serve(&request).await` |
|
||||||
| [Un error 404](../how-to/error-pages.md) | `Err(ErrorPage::NotFound(Some(request)))` |
|
| [Un error 404](../how-to/error-pages.md) | `Err(ErrorPage::NotFound(Some(request)))` |
|
||||||
| [Redirigir](../how-to/routes.md#4-elige-la-respuesta) | `Redirect::see_other("/target")` |
|
| [Redirigir](../how-to/routes.md#4-elige-la-respuesta) | `Redirect::see_other("/target")` |
|
||||||
| [Responder JSON](../how-to/routes.md#4-elige-la-respuesta) | `Json(value)` |
|
| [Responder JSON](../how-to/routes.md#4-elige-la-respuesta) | `Json(value)` |
|
||||||
|
|
@ -98,7 +100,10 @@ Lo esencial de PageTop en una página. Cada línea enlaza con la guía que lo ex
|
||||||
| [Comprobar un permiso](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `has_permission(&request, &MyPermission::X)` |
|
| [Comprobar un permiso](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `has_permission(&request, &MyPermission::X)` |
|
||||||
| [Una página en el panel](../how-to/admin.md) | `DeclareAdminPages::new(declare_pages)` |
|
| [Una página en el panel](../how-to/admin.md) | `DeclareAdminPages::new(declare_pages)` |
|
||||||
| [Leer un ajuste del panel](../how-to/admin.md#4-lee-los-ajustes-guardados) | `pagetop_admin::settings::get_or("app.key", default).await` |
|
| [Leer un ajuste del panel](../how-to/admin.md#4-lee-los-ajustes-guardados) | `pagetop_admin::settings::get_or("app.key", default).await` |
|
||||||
|
| [Enviar un correo](../how-to/mail.md#3-envía-un-correo) | `Email::new().with_to(addr).with_subject("...").with_html(markup).send().await` |
|
||||||
|
| [Un correo traducido](../how-to/mail.md#4-escribe-una-plantilla-traducida) | `Email::from_template(&template, &cx)` |
|
||||||
| [Probar una ruta](../how-to/testing.md) | `web::test::send_request(&app, request).await` |
|
| [Probar una ruta](../how-to/testing.md) | `web::test::send_request(&app, request).await` |
|
||||||
|
| [Comprobar un correo enviado](../how-to/mail.md#comprueba) | `pagetop_mail::outbox::take_to("ana@example.com")` |
|
||||||
|
|
||||||
## Crear un componente
|
## Crear un componente
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -94,9 +94,21 @@ bind_port = 8080
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `bind_address` | Texto | `"localhost"` | Dirección en la que escucha. `"0.0.0.0"` acepta conexiones de fuera |
|
| `bind_address` | Texto | `"localhost"` | Dirección en la que escucha. `"0.0.0.0"` acepta conexiones de fuera |
|
||||||
| `bind_port` | Entero | `8080` | Puerto |
|
| `bind_port` | Entero | `8080` | Puerto |
|
||||||
|
| `max_body_size` | Entero | `2097152` | Tamaño máximo en bytes (2 MiB) de los cuerpos que se leen enteros en memoria (`web::Form`, JSON) y de la suma de los campos de texto de un formulario con archivos; `0`, sin límite. Un cuerpo mayor se rechaza con `413`; en un formulario con archivos, `receive()` devuelve un error del usuario |
|
||||||
| `client_ip_header` | Texto | `""` | Cabecera con la IP del cliente detrás de un proxy inverso (`"X-Forwarded-For"`, `"X-Real-IP"`...); con varias direcciones vale la última; `"Forwarded"` no se admite. Vacía, la de la conexión. Un nombre no válido impide arrancar. Ver [Detrás de un proxy inverso](../how-to/deployment.md#5-detrás-de-un-proxy-inverso) |
|
| `client_ip_header` | Texto | `""` | Cabecera con la IP del cliente detrás de un proxy inverso (`"X-Forwarded-For"`, `"X-Real-IP"`...); con varias direcciones vale la última; `"Forwarded"` no se admite. Vacía, la de la conexión. Un nombre no válido impide arrancar. Ver [Detrás de un proxy inverso](../how-to/deployment.md#5-detrás-de-un-proxy-inverso) |
|
||||||
| `trusted_origins` | Lista | `[]` | Orígenes de otras aplicaciones (`"https://shop.example.com"`) desde los que un navegador puede enviar peticiones que cambian estado (`POST`, `PUT`...); las demás que lleguen de otro origen se rechazan con `403` (protección CSRF). Formato `esquema://servidor[:puerto]`; uno no válido impide arrancar. Ver [Sin *tokens* contra CSRF](../how-to/forms.md#6-sin-tokens-contra-csrf) |
|
| `trusted_origins` | Lista | `[]` | Orígenes de otras aplicaciones (`"https://shop.example.com"`) desde los que un navegador puede enviar peticiones que cambian estado (`POST`, `PUT`...); las demás que lleguen de otro origen se rechazan con `403` (protección CSRF). Formato `esquema://servidor[:puerto]`; uno no válido impide arrancar. Ver [Sin *tokens* contra CSRF](../how-to/forms.md#6-sin-tokens-contra-csrf) |
|
||||||
|
|
||||||
|
## `[upload]`
|
||||||
|
|
||||||
|
Archivos subidos con `web::Upload` (ver [Subir y descargar archivos](../how-to/uploads.md)).
|
||||||
|
|
||||||
|
| Clave | Tipo | Por defecto | Notas |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `dir` | Texto | `"uploads"` | Directorio de los archivos subidos, absoluto o relativo al de trabajo. Se crea al guardar el primer archivo |
|
||||||
|
| `max_file_size` | Entero | `8388608` | Tamaño máximo en bytes (8 MiB) de cada archivo; `0`, sólo limita `max_request_size`. Cada subida puede cambiarlo con `with_max_size()` |
|
||||||
|
| `max_files` | Entero | `20` | Archivos de un mismo envío; `0`, sin límite. Cada subida puede cambiarlo con `with_max_files()` |
|
||||||
|
| `max_request_size` | Entero | `33554432` | Tamaño máximo en bytes (32 MiB) de una petición `multipart/form-data` completa, en lugar de `max_body_size` de `[server]`; `0`, sin límite. Si se supera, `receive()` devuelve un error del usuario con el límite |
|
||||||
|
|
||||||
## `[log]`
|
## `[log]`
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
|
|
|
||||||
|
|
@ -161,7 +161,8 @@ trazas. Con la *feature* `queue`, `send_later()` guarda antes el correo en una c
|
||||||
datos (con `pagetop-seaorm`), que sobrevive a un reinicio y reintenta los fallos temporales, y
|
datos (con `pagetop-seaorm`), que sobrevive a un reinicio y reintenta los fallos temporales, y
|
||||||
`queue()` lo deja en la cola para enviarlo por lotes con `pagetop-cron` (ver
|
`queue()` lo deja en la cola para enviarlo por lotes con `pagetop-cron` (ver
|
||||||
[`[mail.queue]`](configuration.md#mailqueue)). Los enlaces de un correo se construyen con
|
[`[mail.queue]`](configuration.md#mailqueue)). Los enlaces de un correo se construyen con
|
||||||
`absolute_url()`, sobre `mail.base_url`.
|
`absolute_url()`, sobre `mail.base_url`. Paso a paso en [Enviar correo
|
||||||
|
electrónico](../how-to/mail.md).
|
||||||
|
|
||||||
## Tareas programadas
|
## Tareas programadas
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ pagetop-bootsier = { path = "../../../pagetop/extensions/pagetop-bootsier" }
|
||||||
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
||||||
pagetop-cron = { path = "../../../pagetop/extensions/pagetop-cron" }
|
pagetop-cron = { path = "../../../pagetop/extensions/pagetop-cron" }
|
||||||
pagetop-htmx = { path = "../../../pagetop/extensions/pagetop-htmx" }
|
pagetop-htmx = { path = "../../../pagetop/extensions/pagetop-htmx" }
|
||||||
pagetop-mail = { path = "../../../pagetop/extensions/pagetop-mail" }
|
pagetop-mail = { path = "../../../pagetop/extensions/pagetop-mail", features = ["queue"] }
|
||||||
pagetop-seaorm = { path = "../../../pagetop/extensions/pagetop-seaorm", features = ["sqlite"] }
|
pagetop-seaorm = { path = "../../../pagetop/extensions/pagetop-seaorm", features = ["sqlite"] }
|
||||||
pagetop-admin = { path = "../../../pagetop/extensions/pagetop-admin" }
|
pagetop-admin = { path = "../../../pagetop/extensions/pagetop-admin" }
|
||||||
pagetop-user = { path = "../../../pagetop/extensions/pagetop-user" }
|
pagetop-user = { path = "../../../pagetop/extensions/pagetop-user" }
|
||||||
|
|
|
||||||
|
|
@ -9,3 +9,13 @@ max_pool_size = 1
|
||||||
# would hide the result of the checks.
|
# would hide the result of the checks.
|
||||||
[log]
|
[log]
|
||||||
tracing = "Error"
|
tracing = "Error"
|
||||||
|
|
||||||
|
# Mail is kept in memory (see how-to/mail.md), and its links point to a fixed public URL.
|
||||||
|
[mail]
|
||||||
|
transport = "memory"
|
||||||
|
from = "Community garden <garden@example.com>"
|
||||||
|
base_url = "https://garden.example.com"
|
||||||
|
|
||||||
|
# Uploaded files go to the build directory, which git ignores (see how-to/uploads.md).
|
||||||
|
[upload]
|
||||||
|
dir = "target/doccheck-uploads"
|
||||||
|
|
|
||||||
|
|
@ -12,3 +12,9 @@ free-plots = { $count ->
|
||||||
[one] One free plot
|
[one] One free plot
|
||||||
*[other] { $count } free plots
|
*[other] { $count } free plots
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Used by the mail guide (how-to/mail.md).
|
||||||
|
harvest-subject = The tomatoes are ready to pick
|
||||||
|
harvest-greeting = Hello, { $name }:
|
||||||
|
harvest-ready = The tomatoes in the community garden are ripe. Come and pick your share this week.
|
||||||
|
harvest-link = See the harvest calendar
|
||||||
|
|
|
||||||
|
|
@ -12,3 +12,9 @@ free-plots = { $count ->
|
||||||
[one] Una parcela libre
|
[one] Una parcela libre
|
||||||
*[other] { $count } parcelas libres
|
*[other] { $count } parcelas libres
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Used by the mail guide (how-to/mail.md).
|
||||||
|
harvest-subject = Ya se pueden recoger los tomates
|
||||||
|
harvest-greeting = Hola, { $name }:
|
||||||
|
harvest-ready = Los tomates del huerto vecinal ya están maduros. Ven a recoger tu parte esta semana.
|
||||||
|
harvest-link = Ver el calendario de cosecha
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue