summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: b1ffeb612b980be5516471ba616487e27a35b2a9 (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
use std::{mem, fs};

use galemu::{Bound, BoundExt};
use serde::Deserialize;
use failure::Fail;
use futures::{
    Future, Poll, Async,
    try_ready,
    future::{
        self,
        JoinAll, Either, FutureResult
    }
};
use mail_base::Source;

mod serde_impl;
mod base_dir;
mod path_rebase;

pub use self::base_dir::CwdBaseDir;
pub use self::path_rebase::PathRebaseable;

pub trait TemplateEngine {
    type Id: Debug;
    type Error: Fail;

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

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

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

    pub fn load_template_from_path<P>(self, path: P) -> Result<Self, TODO>
        where P: AsRef<Path>
    {
        let content = fs::read_to_string(path)?;
        //TODO choose serde serializer by file extension (toml, json)
        // then serialize to TemplateBase
        // then `base.with_engine(self)`
        load_template_from_str(&content)
    }

    pub fn load_template_from_str(self, desc: &str) -> Result<Self, TODO> {
        self::load_template::from_str(desc)
    }
}

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

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>(raw: &'a D) -> PreparationData<'a, Self::PreparedData>;

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

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

struct InnerTemplate<TE: TemplateEngine> {
    template_name: String,
    base_dir: CwdBaseDir,
    subject: Subject,
    /// 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,
}

type Embeddings = HashMap<String, Resource>;
type Attachments = Vec<Resource>;


pub trait TemplateExt<D, TE> {
    fn prepare_to_render<C>(&self, data: &D, ctx: &C) -> RenderPreparationFuture<TE, D, C>;
}


impl<D, TE> TemplateExt<D, TE> for Template<TE>
    where TE: UseTemplateEngine<D>
{
    fn prepare_to_render<: Context>(&self, data: &D, ctx: &C) ->
        MailPreparationFuture<D, TE, C>
    {
        let preps = self.engine.prepare_data(data);

        let PreparationData {
            inline_embeddings,
            attachments,
            prepare_data
        } = self;

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

        RenderPreparationFuture {
            template: self.clone(),
            context: ctx.clone(),
            prepare_data,
            loading_fut
        }
    }
}

pub struct RenderPreparationFuture<TE, D, C> {
    payload: Option<(
        Template<TE>,
        <TE as UseTemplateEngine<D>>::PreparationData,
        C
    )>,
    loading_fut: Join<
        ResourceContainerLoadingFuture<HashMap<String, Resource>>,
        ResourceContainerLoadingFuture<Vec<Resource>>
    >
}

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

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

        //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<TE, D, C> {
    template: Template<TE>,
    prepared_data: <TE as UseTemplateEngine<D>>::PreparationData,
    ctx: C,
    inline_embeddings: HashMap<String, Resource>,
    attachemnts: Vec<Resource>
}

impl<TE, D, C> Preparations<TE, D, C>
    where TE: TemplateEngine, TE: UseTemplateEngine<D>, C: Context
{
    pub fn render_to_mail_parts(self) -> Result<MailParts, Error> {
        let Preparations {
            template,
            prepared_data,
            ctx,
            //UPS thats a hash map not a Vec
            inline_embeddings: inline_embeddings_from_data,
            attachemnts
        } = self;

        let subject = template.engine().render(
            template.subject_template_id(),
            &prepare_data,
            AdditionalCids::new(&[])
        )?;

        //TODO use Vec1 try_map instead of loop
        let mut bodies = Vec::new();
        for body in template.bodies().iter() {
            let raw = self.engine.render(
                body.template_id(),
                &prepare_data,
                AdditionalCids::new(&[
                    &inline_embeddings
                    body.inline_embeddings(),
                    template.inline_embeddings()
                ])
            )?;

            let data = Data::new(
                raw.into_bytes(),
                Metadata {
                    file_meta: Default::default(),
                    media_type: body.media_type().clone(),
                    content_id: ctx.generate_content_id()
                }
            );

            let inline_embeddings = body.embeddings()
                .values()
                .cloned()
                .collect();

            bodies.push(BodyPart {
                resource: Resource::Data(data)
                inline_embeddings
            });
        }

        Ok(MailParts {
            //UNWRAP_SAFE (complexly mapping a Vec1 is safe)
            alternative_bodies: Vec1::new(bodies).unwrap(),
            inline_embeddings: template.embeddings().values().cloned().collect(),
            attachments: template.attachments().clone()
        })
    }

    pub fn render(self) -> Result<Mail, Error> {
        let parts = self.render_to_mail_parts()?;
        //PANIC_SAFE: templates load all data to at last the point where it has a content id.
        let mail = parts.compose_without_generating_content_ids()?;
        Ok(mail)
    }
}

#[derive(Debug)]
pub struct BodyTemplate<TE: TemplateEngine> {
    template_id: TE::Id,
    media_type: MediaType,
    embeddings: HashMap<String, Resource>
    //TODO potential additional fields like file_name maybe attachments
}

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 embeddings(&self) -> &HashMap<String, Resource> {
        &self.embeddings
    }
}

#[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
    }
}

//--------------------

pub struct AdditionalCids<'a> {
    additional: &'a [&'a HashMap<String, Resource>]
}




// pub struct AdditionalCIds<'a> {
//     additional_resources: &'a [&'a HashMap<String, EmbeddedWithCId>]
// }

// impl<'a> AdditionalCIds<'a> {

//     pub fn new(additional_resources: &'a [&'a H