This repository was archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsubmitTestimonial.js
172 lines (153 loc) · 5.65 KB
/
submitTestimonial.js
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
const uuid = require('uuid/v4')
const ensureSignedIn = require('../../../lib/ensureSignedIn')
const keyCDN = require('../../../lib/keyCDN')
const convertImage = require('../../../lib/convertImage')
const uploadExoscale = require('../../../lib/uploadExoscale')
const logger = require('../../../lib/logger')
const renderUrl = require('../../../lib/renderUrl')
const sendMailTemplate = require('../../../lib/sendMailTemplate')
// const rw = require('rw')
const FOLDER = 'testimonials'
const {IMAGE_SIZE_SMALL, IMAGE_SIZE_SHARE} = convertImage
const MAX_QUOTE_LENGTH = 140
const MAX_ROLE_LENGTH = 60
module.exports = async (_, args, {pgdb, req, t}) => {
ensureSignedIn(req, t)
// check if user is eligitable: has pledged and/or was vouchered a membership
const hasPledges = !!(await pgdb.public.pledges.findFirst({userId: req.user.id}))
if (!hasPledges && !(await pgdb.public.memberships.findFirst({userId: req.user.id}))) {
logger.error('not allowed submitTestimonial', { req: req._log(), args })
throw new Error(t('api/testimonial/pledge/required'))
}
const { role, quote, image } = args
const { ASSETS_BASE_URL, FRONTEND_BASE_URL, S3BUCKET } = process.env
// check max lengths
if (quote.trim().length > MAX_QUOTE_LENGTH) {
logger.error('quote too long', { req: req._log(), args })
throw new Error(t('testimonial/quote/tooLong'))
}
if (role.trim().length > MAX_ROLE_LENGTH) {
logger.error('role too long', { req: req._log(), args })
throw new Error(t('testimonial/role/tooLong'))
}
// test with local image
// const inputFile = rw.readFileSync(__dirname+'/../image.b64', 'utf8')
// const inputBuffer = new Buffer(inputFile, 'base64')
let sendConfirmEmail = false
let testimonial
testimonial = await pgdb.public.testimonials.findOne({userId: req.user.id})
if (!testimonial || !testimonial.published) { sendConfirmEmail = true }
if (!testimonial && !image) {
logger.error('a new testimonials requires an image', { req: req._log(), args })
throw new Error(t('api/testimonial/image/required'))
}
// block if testimonial has a video
if (testimonial && testimonial.video) {
logger.error('testimonial has a video, change not allowed', { req: req._log(), args })
throw new Error(t('api/unexpected'))
}
const firstMembership = await pgdb.public.memberships.findFirst({userId: req.user.id}, {orderBy: ['sequenceNumber asc']})
let seqNumber
if (firstMembership) { seqNumber = firstMembership.sequenceNumber }
if (!image) {
testimonial = await pgdb.public.testimonials.updateAndGetOne({id: testimonial.id}, {
role,
quote,
published: true,
sequenceNumber: testimonial.sequenceNumber || seqNumber
}, {skipUndefined: true})
} else { // new image
const inputBuffer = Buffer.from(image, 'base64')
const id = testimonial ? testimonial.id : uuid()
const pathOriginal = `/${FOLDER}/${id}_original.jpeg`
const pathSmall = `/${FOLDER}/${id}_${IMAGE_SIZE_SMALL}x${IMAGE_SIZE_SMALL}.jpeg`
const pathShare = `/${FOLDER}/${id}_${IMAGE_SIZE_SHARE}x${IMAGE_SIZE_SHARE}.jpeg`
await Promise.all([
convertImage.toJPEG(inputBuffer)
.then((data) => {
return uploadExoscale({
stream: data,
path: pathOriginal,
mimeType: 'image/jpeg',
bucket: S3BUCKET
})
}),
convertImage.toSmallBW(inputBuffer)
.then((data) => {
return uploadExoscale({
stream: data,
path: pathSmall,
mimeType: 'image/jpeg',
bucket: S3BUCKET
})
}),
convertImage.toShare(inputBuffer)
.then((data) => {
return uploadExoscale({
stream: data,
path: pathShare,
mimeType: 'image/jpeg',
bucket: S3BUCKET
})
})
])
if (testimonial) {
await keyCDN.purgeUrls([pathOriginal, pathSmall, pathShare])
testimonial = await pgdb.public.testimonials.updateAndGetOne({id: testimonial.id}, {
role,
quote,
image: ASSETS_BASE_URL + pathSmall,
updatedAt: new Date(),
published: true,
sequenceNumber: testimonial.sequenceNumber || seqNumber
}, {skipUndefined: true})
} else {
testimonial = await pgdb.public.testimonials.insertAndGet({
id,
userId: req.user.id,
role,
quote,
image: ASSETS_BASE_URL + pathSmall,
published: true,
sequenceNumber: seqNumber
}, {skipUndefined: true})
}
}
// generate sm picture (PNG!)
try {
const smImagePath = `/${FOLDER}/sm/${testimonial.id}_sm.png`
await renderUrl(`${FRONTEND_BASE_URL}/community?share=${testimonial.id}`, 1200, 628)
.then(async (data) => {
return uploadExoscale({
stream: data,
path: smImagePath,
mimeType: 'image/png',
bucket: S3BUCKET
}).then(async () => {
await keyCDN.purgeUrls([smImagePath])
return pgdb.public.testimonials.updateAndGetOne({id: testimonial.id}, {
smImage: ASSETS_BASE_URL + smImagePath
})
})
})
} catch (e) {
logger.error('sm image render failed', { req: req._log(), args, e })
console.error(e)
}
if (sendConfirmEmail) {
await sendMailTemplate({
to: req.user.email,
fromEmail: process.env.DEFAULT_MAIL_FROM_ADDRESS,
subject: t('api/testimonial/mail/subject'),
templateName: 'cf_community',
globalMergeVars: [
{ name: 'NAME',
content: req.user.firstName + ' ' + req.user.lastName
}
]
})
}
// augement with name
testimonial.name = `${req.user.firstName} ${req.user.lastName}`
return testimonial
}