summaryrefslogtreecommitdiff
path: root/lib/awmail/index.js
blob: e516a44ac53e5175c8aa8f71a67d38bc8fec9d83 (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
var Liquid = require('liquid-node')
var fs = require('fs')
var Q = require('q')
var htmlTemplate = fs.readFileSync('templates/email.html', 'utf8')
var textTemplate = fs.readFileSync('templates/email.txt', 'utf8')
var mailgun = require('mailgun.js')
var request = require('request')
var multer = require('multer')
var PassThrough = require('stream').PassThrough
var upload = require('../../node_modules/okcms/app/node_modules/okservices/oks3/upload')
var uuid = require('uuid/v1')

/*
  awmail: {
    lib: require("./lib/awmail"),
    apikey: process.env.MAILGUN_API_KEY,
    domain: process.env.MAILGUN_DOMAIN,
    from: 'Postmaster <mail@example.com>',
    subject: 'Your Result',
  }
*/

function AWMail (options) {
  if (!(this instanceof AWMail)) return new AWMail(options)
  options = options || {}
  if (!options.express)
    throw new Error('Express not provided to AWMail')
  if (!options.config)
    throw new Error('Configuration not provided to AWMail')

  var express = options.express
  var router = express.Router()
  var config = options.config

  var mult = multer()
  var engine = new Liquid.Engine

  var mg = mailgun.client({
    username: 'api',
    key: process.env.MAILGUN_API_KEY,
  })

  var multerMiddleware = mult.fields([
    { name: 'dots', maxCount: 1 },
    { name: 'lines', maxCount: 1 },
    { name: 'plain', maxCount: 1 },
  ])
  
  var logoImage = fs.readFileSync('../../public/assets/img/logo.png')
  var armoryImage = fs.readFileSync('../../public/assets/img/armory.png')

  router.post('/send', multerMiddleware, function (req, res) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  
    var id = uuid()
    var email = req.body.email
    var track = req.body.track
    var secret = req.body.secret
    var dots_url, lines_url, plain_url

    if (secret !== config.secret) {
      return res.sendStatus(500)
    }
    
    deferToNextTick().then(function(){
      console.log("upload dots")
      return uploadImage({
        filename: id + '-dots.jpg',
        file: req.files.dots[0],
      })
    }).then(function(url){
      console.log("upload lines")
      dots_url = url
      return uploadImage({
        filename: id + '-lines.jpg',
        file: req.files.lines[0],
      })
    }).then(function(url){
      console.log("upload plain")
      lines_url = url
      return uploadImage({
        filename: id + '-plain.jpg',
        file: req.files.plain[0],
      })
    }).then(function(url){
      plain_url = url
      console.log("parse templates")
      // https://marsupial.s3.amazonaws.com/armory/mail/260b1e90-380e-11e7-b0c0-190f661d482a.jpg
      var templateData = {
        id: id,
        email: email,
      }
      return parseTemplates(templateData)
    }).then(function(mailData){
      console.log("send mail")
      mailData.email = email
      mailData.image = req.files.plain[0]
      return sendMail(mailData)
    }).then(function(){
      console.log("store email")
      if (String(track) === 'true') {
        return storeEmail(email)
      } else {
        return Q.Promise(function(resolve, reject, notify) { resolve() })
      }
    }).then(function(){
      console.log("all done")
    }).catch(function(err){
      console.error(err.stack)
    })

    res.sendStatus(200)
  })

  router.post('/feedback', mult.array(), function (req, res) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  
    var name = req.body.name
    var email = req.body.email
    var message = req.body.message
    var track = req.body.track
    var secret = req.body.secret
    var publish = req.body.publish

    if (secret !== config.secret) {
      return res.sendStatus(500)
    }
    
    deferToNextTick().then(function(){
      console.log("store message")
      return storeMessage(name, email, message, publish)
    }).then(function(){
      console.log("store email")
      if (String(track) === 'true') {
        return storeEmail(email)
      } else {
        return Q.Promise(function(resolve, reject, notify) { resolve() })
      }
    }).then(function(){
      console.log("all done")
    }).catch(function(err){
      console.error(err.stack)
    })

    res.sendStatus(200)
  })

  router.get('/test', function (req, res) {
    var hash = 'test'
    var email = 'julescarbon@gmail.com'
    deferToNextTick().then(function(){
      console.log("parse templates")
      var templateData = {
        email: email,
        hash: hash,
      }
      return parseTemplates(templateData)
    }).then(function(mailData){
      console.log("send mail")
      mailData.email = email
      return sendMail(mailData)
    }).then(function(){
      console.log("store email")
      return storeEmail(email)
    }).then(function(){
      console.log("all done")
    }).catch(function(err){
      console.log(err)
    })

    res.sendStatus(200)
  })
  
  function deferToNextTick(){
    return Q.Promise(function(resolve, reject, notify) {
      process.nextTick(function(){
        resolve()
      })
    })
  }

  function uploadImage (data){
    return Q.Promise(function(resolve, reject, notify) {
      upload.put({
        file: data.file,
        filename: data.filename,
        dirname: "armory/mail",
        types: {
          'image/gif': 'gif',
          'image/jpeg': 'jpg',
          'image/jpg': 'jpg',
          'image/png': 'png',
        },
        unacceptable: function(err){
          reject(new Error("S3 error: " + err))
        },
        success: function(url){
          resolve(url)
        }
      })
    })
  }
  
  function parseTemplates (data){
    return Q.Promise(function(resolve, reject, notify) {
      engine.parseAndRender(textTemplate, data).then(function(textResult){
        engine.parseAndRender(htmlTemplate, data).then(function(htmlResult){
          resolve({
            text: textResult,
            html: htmlResult
          })
        }).catch(function(){ reject(new Error("Error building text template")) })
      }).catch(function(){ reject(new Error("Error building html template")) })
    })
  }
  
  function sendMail (content){
    var image = new PassThrough()
    image.path = 'face.jpg'
    image.end(content.image.buffer)

    var logo = new PassThrough()
    logo.path = 'logo.jpg'
    logo.end(logoImage)

    var armory = new PassThrough()
    armory.path = 'armory.jpg'
    armory.end(armoryImage)

    return mg.messages.create(config.domain, {
      from: config.from,
      to: [content.email],
      subject: config.subject,
      text: content.text,
      html: content.html,
      inline: [image, logo, armory],
    })
  }
  
  function storeEmail (mail){
    return Q.Promise(function(resolve, reject, notify) {
      var data = {}
      data['Email'] = mail
      data['entry.1571194529'] = mail
      data['fvv'] = "1"
      
      var url = "https://docs.google.com/forms/d/e/1FAIpQLSfBdSrjLyoZwnttbeQ5v_kuW8n9k9CGWfXDSHTNixHOlvsxCg/formResponse"

      request({ url: url, qs: data }, function (err, response, body) {
        if (err || response.statusCode !== 200) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }
  
  function storeMessage (name, mail, message,publish){
    return Q.Promise(function(resolve, reject, notify) {
      var data = {}
      data['Name'] = name
      data['entry.828397709'] = name
      data['Email'] = mail
      data['entry.1436672940'] = mail
      data['Message'] = message
      data['entry.2103257301'] = message
      data['Publish'] = publish ? 'x' : ''
      data['entry.125849372'] = publish ? 'x' : ''
      data['fvv'] = "1"
      
      var url = "https://docs.google.com/forms/d/e/1FAIpQLSdWDnpy4ZF1dJwfAcX5CUITpjbLqLC7rS7nr2iSQrEeGXM1bQ/formResponse"

      request({ url: url, qs: data }, function (err, response, body) {
        if (err || response.statusCode !== 200) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }
  
  this._router = router
}

AWMail.prototype.middleware = function () {
  return this._router
}

module.exports = AWMail