-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
263 lines (239 loc) · 8.3 KB
/
index.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
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
const Webflow = require('webflow-api');
const Jimp = require('jimp');
const AWS = require('aws-sdk');
const probe = require('probe-image-size');
require('dotenv').config();
const limit = 100; //controls amount of items per collection to process (max: 100)
const sizingRegEx = /(\d{1,4})x(\d{1,4})/gm;
function Resizer(config) {
this.config = config;
this.s3 = new AWS.S3({ region: config.aws.region });
this.webflow = new Webflow({ token: this.config.webflow.token });
}
Resizer.prototype.onResizeSite = function (siteId) {
const collections = this.webflow.collections({ siteId: siteId })
return collections.then(collections => {
var fetchPromises = []
collections.forEach(collection => {
fetchPromises.push(
this.webflow.collection({ collectionId: collection._id })
)
})
return fetchPromises
}).then(collectionFetchPromises => {
return Promise.all(collectionFetchPromises).then(
collections => {
return collections
}
)
}).then(
collections => {
collectionsWithImagesFields = []
collections.forEach(c => {
var imagesFields = this.getImagesFieldsFromCollection(c);
if (0 !== imagesFields.length) {
collectionsWithImagesFields.push({
collectionId: c._id,
fields: imagesFields
})
}
})
return collectionsWithImagesFields;
}
).then(
collectionsFieldsWithImages => {
var processedItemsPromises = [];
collectionsFieldsWithImages.forEach(collectionFields => {
processedItemsPromises.push(
this.getAllItems(collectionFields)
.then(
collectionItems => {
collectionItems = collectionItems.map(page => {
page.fields = collectionFields.fields
return this.processItems(page);
})
return collectionItems
}
)
)
})
return processedItemsPromises
}
).then(
processedItemsPromises => {
return Promise.all(processedItemsPromises).then(
processedItems => {
return processedItems[0]
}
)
}
).then(
processedCollections => {
var flattenedItems = []
processedCollections.forEach(collectionItems => {
collectionItems.forEach(item => {
flattenedItems.push(item)
})
})
return flattenedItems;
}
).then(
flattenedItems => {
var validationSizes = []
flattenedItems.forEach(
item => {
validationSizes.push(this.validateImageSize(item))
}
)
return validationSizes;
}
).then(
validatedItemsPromises => {
return Promise.all(validatedItemsPromises).then(
validatedItems => {
return validatedItems.filter(n => n)
}
)
}
).then(
filteredItems => {
if (0 === filteredItems.length) {
return 0;
} else {
var sizeChangePromises = [];
filteredItems.forEach(
filteredItem => {
sizeChangePromises.push(this.changeSize(filteredItem))
}
)
return sizeChangePromises
}
}
)
}
Resizer.prototype.getAllItems = function (collection) {
let itemsPromises = [];
return this.webflow.items({ collectionId: collection.collectionId }, { limit: limit })
.then(res => {
itemsPromises.push(res);
if (res.total > res.limit) {
let runs = Math.ceil(res.total / limit);
for (i = 1; i < runs; i++) {
itemsPromises.push(this.webflow.items(
{ collectionId: collection.collectionId },
{ limit: limit, offset: limit * i },
)
)
}
}
return Promise.all(itemsPromises);
})
}
Resizer.prototype.getImagesFieldsFromCollection = function (collection) {
var imagesFields = [];
for (var i = 0; i < collection.fields.length; i++) {
if (collection.fields[i].type === "ImageRef" &&
collection.fields[i].helpText.match(sizingRegEx) !== null) {
imagesFields.push(collection.fields[i]);
}
}
return imagesFields;
}
//Processes all items in collection
Resizer.prototype.processItems = function (collectionItems) {
var itemsImages = []
collectionItems.fields.forEach((field) => {
collectionItems.items.forEach((item) => {
let size = field.helpText.match(sizingRegEx);
let imgSize = size[0].split('x');
let itemDetails = {
'collectionId': item._cid,
'itemId': item._id,
'itemName': item.name,
'itemSlug': item.slug,
'imageUrl': item[`${field.slug}`].url,
'fieldName': field.slug,
'fieldId': field.id,
'width': Number(imgSize[0]),
'height': Number(imgSize[1])
}
if (itemDetails.height !== 0 && itemDetails.width !== 0) {
itemsImages.push(itemDetails)
}
})
});
return itemsImages
}
Resizer.prototype.validateImageSize = function (itemDetails) {
if (itemDetails.height !== 0 && itemDetails.width !== 0) {
return probe(itemDetails.imageUrl)
.then(
result => {
if (result.width > itemDetails.width || result.height > itemDetails.height) {
return itemDetails;
} else {
return null
}
}
);
}
}
Resizer.prototype.changeSize = function (itemDetails) {
return Jimp.read(itemDetails.imageUrl)
.then(image => {
return image
.scaleToFit(itemDetails.width, itemDetails.height) // resize
.quality(100) // set JPEG quality
.getBufferAsync(Jimp.MIME_JPEG)
})
.then(img => {
return this.uploadToAws(img, itemDetails);
})
.catch(err => {
console.error(
'error scaling the image',
err,
itemDetails
);
});
};
Resizer.prototype.uploadToAws = function (img, itemDetails) {
let myBucket = this.config.aws.bucket;
let myKey = `${itemDetails.itemId}-${itemDetails.fieldId}.jpg`;
let params = { Bucket: myBucket, Key: myKey, Body: img };
return this.s3.putObject(params, function (err, data) {
if (err) {
console.error(
'error during upload to s3',
err,
itemDetails
)
}
}).promise().then(
res => {
return this.updateWebflow(itemDetails)
}
)
}
Resizer.prototype.updateWebflow = function (itemDetails) {
let url = `https://s3.${this.config.aws.region}.amazonaws.com/${this.config.aws.bucket}/${itemDetails.itemId}-${itemDetails.fieldId}.jpg`;
let field = `${itemDetails.fieldName}`;
let fieldsObject = {
collectionId: itemDetails.collectionId,
itemId: itemDetails.itemId,
fields: {
'name': itemDetails.itemName,
'slug': itemDetails.itemSlug,
'_archived': false,
'_draft': false,
}
}
fieldsObject.fields[field] = url;
const item = this.webflow.updateItem(fieldsObject)
.catch(err => {
console.error(err, itemDetails);
});
return item.then(i => console.log(`Updated ${field} of '${itemDetails.itemName}' in Collection: '${itemDetails.collectionId}'`))
}
exports.default = Resizer;
module.exports = exports['default'];