summaryrefslogtreecommitdiffstats
path: root/template/src/lib.rs
blob: 7a96b06df66f2522ffba02f00563b2541131f13d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
extern crate failure;
extern crate serde;
extern crate futures;
extern crate mail_core;
extern crate mail_headers;
extern crate vec1;
extern crate toml;
extern crate maybe_owned;
#[cfg(feature="handlebars")]
extern crate handlebars as hbs;

#[cfg(all(feature="handlebars", not(feature="handlebars-bindings")))]
compile_error!("use feature `handlebars-bindings` instead of opt-dep-auto-feature `handlebars`");

use std::{
    fs,
    collections::HashMap,
    fmt::Debug,
    path::{Path, PathBuf},
    ops::Deref
};

use serde::{
    Serialize,
    Deserialize
};
use failure::Error;
use futures::{
    Future, Poll, Async,
    try_ready,
    future::{self, Join, Either}
};
use vec1::Vec1;
use maybe_owned::MaybeOwned;

use mail_core::{
    Resource,
    Data, Metadata,
    Context, ResourceContainerLoadingFuture,
    compose::{MailParts, BodyPart},
    Mail
};
use mail_headers::{
    HeaderKind, Header,
    header_components::MediaType,
    headers
};

mod base_dir;
mod path_rebase;
mod additional_cid;
pub mod serde_impl;
pub mod error;

#[cfg(feature="handlebars")]
pub mod handlebars;

pub use self::base_dir::*;
pub use self::path_rebase::*;
pub use self::additional_cid::*;

/// Trait used to bind/implement template engines.
pub trait TemplateEngine: Sized {
    type Id: Debug;

    type LazyBodyTemplate: PathRebaseable + Debug + Send + Serialize + for<'a> Deserialize<'a>;

    fn load_body_template(&mut self, tmpl: Self::LazyBodyTemplate)
        -> Result<BodyTemplate<Self>, Error>;

    fn load_subject_template(&mut self, template_string: String)
        -> Result<Self::Id, Error>;
}

/// Additional trait a template engine needs to implement for the types it can process as input.
///
/// This could for example be implemented in a wild card impl for the template engine for
/// any data `D` which implements `Serialize`.
pub trait TemplateEngineCanHandleData<D>: TemplateEngine {

    fn render<'r, 'a>(
        &'r self,
        id: &'r Self::Id,
        data: &'r D,
        additional_cids: AdditionalCIds<'r>
    ) -> Result<String, Error>;
}

/// Load a template as described in a toml file.
///
/// This will set the default of the base_dir to the
/// dir the template file loaded is in.
pub fn load_toml_template_from_path<TE, C>(
    engine: TE,
    path: PathBuf,
    ctx: &C
) -> impl Future<Item=Template<TE>, Error=Error>
    where TE: TemplateEngine + 'static, C: Context
{

    let ctx2 = ctx.clone();
    ctx.offload_fn(move || {
        let content = fs::read_to_string(&path)?;
        let base: serde_impl::TemplateBase<TE> = toml::from_str(&content)?;
        let base_dir = path.parent().unwrap_or_else(||Path::new("."));
        let base_dir = CwdBaseDir::from_path(base_dir)?;
        Ok((base, base_dir))
    }).and_then(move |(base, base_dir)| base.load(engine, base_dir, &ctx2))
}

/// Load a template as described in a toml string;
pub fn load_toml_template_from_str<TE, C>(
    engine: TE,
    content: &str,
    ctx: &C
) -> impl Future<Item=Template<TE>, Error=Error>
    where TE: TemplateEngine, C: Context
{
    let base: serde_impl::TemplateBase<TE> =
        match toml::from_str(content) {
            Ok(base) => base,
            Err(err) => { return Either::B(future::err(Error::from(err))); }
        };

    let base_dir =
        match CwdBaseDir::from_path(Path::new(".")) {
            Ok(base_dir) => base_dir,
            Err(err) => { return Either::B(future::err(Error::from(err))) }
        };

    Either::A(base.load(engine, base_dir, ctx))
}


/// A Mail template.
#[derive(Debug)]
pub struct Template<TE: TemplateEngine> {
    template_name: String,
    base_dir: CwdBaseDir,
    subject: Subject<TE>,
    /// This can only be in the loaded form _iff_ this is coupled
    /// with a template engine instance, as using it with the wrong
    /// template engine will lead to potential bugs and panics.
    bodies: Vec1<BodyTemplate<TE>>,
    //TODO: make sure
    embeddings: HashMap<String, Resource>,
    attachments: Vec<Resource>,
    engine: TE,
}

impl<TE> Template<TE>
    where TE: TemplateEngine
{
    pub fn inline_embeddings(&self) -> &HashMap<String, Resource> {
        &self.embeddings
    }

    pub fn attachments(&self) -> &[Resource] {
        &self.attachments
    }

    pub fn engine(&self) -> &TE {
        &self.engine
    }

    pub fn bodies(&self) -> &[BodyTemplate<TE>] {
        &self.bodies
    }

    pub fn subject_template_id(&self) -> &TE::Id {
        &self.subject.template_id
    }
}


/// Represents one of potentially many alternate bodies in a template.
#[derive(Debug)]
pub struct BodyTemplate<TE: TemplateEngine> {
    pub template_id: TE::Id,
    pub media_type: MediaType,
    pub inline_embeddings: HashMap<String, Resource>
}

impl<TE> BodyTemplate<TE>
    where TE: TemplateEngine
{
    pub fn template_id(&self) -> &TE::Id {
        &self.template_id
    }

    pub fn media_type(&self) -> &MediaType {
        &self.media_type
    }

    pub fn inline_embeddings(&self) -> &HashMap<String, Resource> {
        &self.inline_embeddings
    }
}

/// Represents a template used for generating the subject of a mail.
#[derive(Debug)]
pub struct Subject<TE: TemplateEngine> {
    template_id: TE::Id
}

impl<TE> Subject<TE>
    where TE: TemplateEngine
{
    pub fn template_id(&self) -> &TE::Id {
        &self.template_id
    }
}

/// Automatically provides the `prepare_to_render` method for all `Templates`
///
/// This trait is implemented for all `Templates`/`D`(data) combinations where
/// the templates template engine can handle the given data (impl. `TemplateEngineCanHandleData<D>`)
///
/// This trait should not be implemented by hand.
pub trait TemplateExt<TE, D>
    where TE: TemplateEngine + TemplateEngineCanHandleData<D>
{

    fn render_to_mail_parts<'r>(&self, data: LoadedTemplateData<'r, D>, ctx: &impl Context)
        -> Result<(MailParts, Header<headers::Subject>), Error>;

    fn render<'r>(&self, data: LoadedTemplateData<'r, D>, ctx: &impl Context) -> Result<Mail, Error> {
        let (parts, subject) = self.render_to_mail_parts(data, ctx)?;
        let mut mail = parts.compose();
        mail.insert_header(subject);
        Ok(mail)
    }
}


impl<TE, D> TemplateExt<TE, D> for Template<TE>
    where TE: TemplateEngine + TemplateEngineCanHandleData<D>
{
    fn render_to_mail_parts<'r>(&self, data: LoadedTemplateData<'r, D>, ctx: &impl Context)
        -> Result<(MailParts, Header<headers::Subject>), Error>
    {
        let TemplateData {
            data,
            inline_embeddings,
            mut attachments
        } = data.into();

        let subject = self.engine().render(
            self.subject_template_id(),
            &data,
            AdditionalCIds::new(&[])
        )?;

        let subject = headers::Subject::auto_body(subject)?;

        //TODO use Vec1 try_map instead of loop
        let mut bodies = Vec::new();
        for body in self.bodies().iter() {
            let raw = self.