summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 5ffe1d978048697741165bd7af3f7733a12b6bcf (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
extern crate failure;
extern crate serde;
extern crate futures;
extern crate galemu;
extern crate mail_core;
extern crate mail_headers;
extern crate vec1;
extern crate toml;

use std::{
    fs,
    collections::HashMap,
    fmt::Debug,
    path::{PathBuf},
    sync::Arc
};

use serde::{
    Serialize,
    Deserialize
};
use galemu::{Bound, BoundExt};
use failure::{Fail, Error};
use futures::{
    Future, Poll, Async,
    try_ready,
    future::{self, Join, Either}
};
use vec1::Vec1;

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

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

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

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

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>;
}

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)?;
        Ok(base)
    }).and_then(move |base| base.load(engine, &ctx2))
}

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))); }
        };

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

pub struct PreparationData<'a, PD: for<'any> BoundExt<'any>> {
    pub attachments: Vec<Resource>,
    pub inline_embeddings: HashMap<String, Resource>,
    pub prepared_data: Bound<'a, PD>
}

pub trait UseTemplateEngine<D>: TemplateEngine {

    //TODO[doc]: this is needed for all template engines which use to json serialization
    // (we have more then one template so there would be a lot of overhead)
    type PreparedData: for<'a> BoundExt<'a>;

    //TODO[design]: allow returning a result
    fn prepare_data<'a>(&self, raw: &'a D) -> PreparationData<'a, Self::PreparedData>;

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

#[derive(Debug)]
pub struct Template<TE: TemplateEngine> {
    inner: Arc<InnerTemplate<TE>>
}

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

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

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

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

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

impl<TE> Clone for Template<TE>
    where TE: TemplateEngine
{
    fn clone(&self) -> Self {
        Template { inner: self.inner.clone() }
    }
}

#[derive(Debug)]
struct InnerTemplate<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,
}


pub trait TemplateExt<TE, D>
    where TE: TemplateEngine + UseTemplateEngine<D>
{
    fn prepare_to_render<'s, 'r, C>(&'s self, data: &'r D, ctx: &'s C) -> RenderPreparationFuture<'r, TE, D, C>
        where C: Context;
}


impl<TE, D> TemplateExt<TE, D> for Template<TE>
    where TE: TemplateEngine + UseTemplateEngine<D>
{
    fn prepare_to_render<'s, 'r, C>(&'s self, data: &'r D, ctx: &'s C) -> RenderPreparationFuture<'r, TE, D, C>
        where C: Context
    {
        let preps = self.inner.engine.prepare_data(data);

        let PreparationData {
            inline_embeddings,
            attachments,
            prepared_data
        } = preps;

        let loading_fut = Resource::load_container(inline_embeddings, ctx)
            .join(Resource::load_container(attachments, ctx));

        RenderPreparationFuture {
            payload: Some((
                self.clone(),
                prepared_data,
                ctx.clone()
            )),
            loading_fut
        }
    }
}

pub struct RenderPreparationFuture<'a, TE, D, C>
    where TE: TemplateEngine + UseTemplateEngine<D>, C: Context
{
    payload: Option<(
        Template<TE>,
        Bound<'a, <TE as UseTemplateEngine<D>>::PreparedData>,
        C
    )>,
    loading_fut: Join<
        ResourceContainerLoadingFuture<HashMap<String, Resource>>,
        ResourceContainerLoadingFuture<Vec<Resource>>
    >
}

impl<'a, TE,D,C> Future for RenderPreparationFuture<'a, TE, D, C>
    where TE: TemplateEngine, TE: UseTemplateEngine<D>, C: Context
{
    type Item = Preparations<'a, TE, D, C>;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (
            inline_embeddings,
            attachments
        ) = try_ready!(self.loading_fut.poll());

        //UNWRAP_SAFE only non if polled after resolved
        let (template, prepared_data, ctx) = self.payload.take().unwrap();

        Ok(Async::Ready(Preparations {
            template,
            prepared_data,
            ctx,
            inline_embeddings,
            attachments
        }))
    }
}

pub struct Preparations<'a, TE, D, C>
    where TE: TemplateEngine + UseTemplateEngine<D>, C: Context
{
    template: Template<TE&