-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcloudinary.js
More file actions
295 lines (234 loc) · 7.12 KB
/
cloudinary.js
File metadata and controls
295 lines (234 loc) · 7.12 KB
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
const crypto = require('crypto');
const path = require('path');
const fetch = require('node-fetch');
const { JSDOM } = require('jsdom');
const cloudinary = require('cloudinary').v2;
const { isRemoteUrl, determineRemoteUrl } = require('./util');
const { ERROR_CLOUD_NAME } = require('../data/errors');
/**
* getCloudinary
*/
function getCloudinary(config) {
if ( !config ) return cloudinary;
return configureCloudinary(config);
}
module.exports.getCloudinary = getCloudinary;
/**
* configureCloudinary
*/
function configureCloudinary(config = {}) {
cloudinary.config({
cloud_name: config.cloudName,
api_key: config.apiKey,
api_secret: config.apiSecret
});
return cloudinary;
}
module.exports.configureCloudinary = configureCloudinary;
/**
* createPublicId
*/
async function createPublicId({ path: filePath } = {}) {
let hash = crypto.createHash('md5');
const { name: imgName } = path.parse(filePath);
if ( !isRemoteUrl(filePath) ) {
hash.update(filePath);
} else {
const response = await fetch(filePath);
const buffer = await response.buffer();
hash.update(buffer);
}
hash = hash.digest('hex');
return `${imgName}-${hash}`
}
module.exports.createPublicId = createPublicId;
/**
* getCloudinaryUrl
*/
async function getCloudinaryUrl(options = {}) {
const {
deliveryType,
folder,
path: filePath,
localDir,
remoteHost,
uploadPreset,
sizes
} = options;
const { cloud_name: cloudName, api_key: apiKey, api_secret: apiSecret } = cloudinary.config();
const canSignUpload = apiKey && apiSecret;
if ( !cloudName ) {
throw new Error(ERROR_CLOUD_NAME);
}
if ( deliveryType === 'upload' && !canSignUpload && !uploadPreset ) {
throw new Error(`To use deliveryType ${deliveryType}, please use an uploadPreset for unsigned requests or an API Key and Secret for signed requests.`);
}
let fileLocation;
let publicId;
let srcset; //mine
if ( deliveryType === 'fetch' ) {
// fetch allows us to pass in a remote URL to the Cloudinary API
// which it will cache and serve from the CDN, but not store
fileLocation = determineRemoteUrl(filePath, remoteHost);
publicId = fileLocation;
} else if ( deliveryType === 'upload' ) {
// upload will actually store the image in the Cloudinary account
// and subsequently serve that stored image
// If our image is locally sourced, we need to obtain the full
// local relative path so that we can tell Cloudinary where
// to upload from
let fullPath = filePath;
// if ( !isRemoteUrl(fullPath) ) {
// fullPath = path.join(localDir, fullPath);
// }
const id = await createPublicId({
path: fullPath
});
const uploadOptions = {
folder,
public_id: id,
overwrite: false,
eager: sizes.map(({ width, height, crop }) => ({
width,
height,
crop
}))
};
if ( uploadPreset ) {
uploadOptions.upload_preset = uploadPreset;
}
let results;
if ( canSignUpload ) {
// We need an API Key and Secret to use signed uploading
results = await cloudinary.uploader.upload(fullPath, {
...uploadOptions
});
} else {
// If we want to avoid signing our uploads, we don't need our API Key and Secret,
// however, we need to provide an uploadPreset
results = await cloudinary.uploader.unsigned_upload(fullPath, uploadPreset, {
...uploadOptions
});
}
// console.log("RESULTS!!: ", results);
// Finally use the stored public ID to grab the image URL
const { public_id } = results;
publicId = public_id;
fileLocation = fullPath;
// srcset uses url from results
srcset = results.eager.map(({ url }) => url);
}
const cloudinaryUrl = cloudinary.url(publicId, {
type: deliveryType,
secure: true,
transformation: [
{
fetch_format: 'auto',
quality: 'auto'
}
]
});
return {
sourceUrl: fileLocation,
cloudinaryUrl,
publicId,
srcset
};
}
module.exports.getCloudinaryUrl = getCloudinaryUrl;
/**
* updateHtmlImagesToCloudinary
*/
// function to check for assets previously build by Cloudinary
function getAsset(imgUrl, assets){
const cloudinaryAsset= assets && Array.isArray(assets.images) && assets.images.find(({ publishPath, publishUrl } = {}) => {
return [publishPath, publishUrl].includes(imgUrl);
});
return cloudinaryAsset;
}
async function updateHtmlImagesToCloudinary(html, options = {}) {
const {
assets,
deliveryType,
uploadPreset,
folder,
localDir,
remoteHost,
loadingStrategy = 'lazy',
sizes
} = options;
const errors = [];
const dom = new JSDOM(html);
console.log("SIZES:",sizes)
// Loop through all images found in the DOM and swap the source with
// a Cloudinary URL
const images = Array.from(dom.window.document.querySelectorAll('img'));
for ( const $img of images ) {
let imgSrc = $img.getAttribute('src');
let cloudinaryUrl;
// Check to see if we have an existing asset already to pick from
// Look at both the path and full URL
const asset = getAsset(imgSrc, assets);
if ( asset && deliveryType === 'upload' ) {
cloudinaryUrl = asset.cloudinaryUrl;
}
let urlsrcset;
// If we don't have an asset and thus don't have a Cloudinary URL, create
// one for our asset
if ( !cloudinaryUrl ) {
try {
const { cloudinaryUrl: url, srcset:srcset } = await getCloudinaryUrl({
deliveryType,
folder,
path: imgSrc,
localDir,
uploadPreset,
remoteHost,
loadingStrategy,
sizes
});
cloudinaryUrl = url;
urlsrcset = srcset;
// console.log(urlsrcset)
} catch(e) {
const { error } = e;
errors.push({
imgSrc,
message: e.message || error.message
});
continue;
}
}
console.log(urlsrcset)
$img.setAttribute('src', cloudinaryUrl);
$img.setAttribute('loading', loadingStrategy);
// convert srcset images to cloudinary
const srcset = $img.getAttribute('srcset');
if (srcset) {
// convert all srcset urls to cloudinary urls using getCloudinaryUrl function in a Promise.all
const srcsetUrls = srcset.split(',').map((url) => url.trim().split(' '));
const srcsetUrlsPromises = srcsetUrls.map((url) =>{
const exists = getAsset(url[0],assets);
if ( exists && deliveryType === 'upload' ) {
return exists.cloudinaryUrl;
}
return getCloudinaryUrl({
deliveryType,
folder,
path: url[0],
localDir,
uploadPreset,
remoteHost
})
});
const srcsetUrlsCloudinary = await Promise.all(srcsetUrlsPromises);
const srcsetUrlsCloudinaryString = srcsetUrlsCloudinary.map((urlCloudinary, index) => `${urlCloudinary.cloudinaryUrl} ${srcsetUrls[index][1]}`).join(', ');
$img.setAttribute('srcset', srcsetUrlsCloudinaryString);
}
}
return {
html: dom.serialize(),
errors
}
}
module.exports.updateHtmlImagesToCloudinary = updateHtmlImagesToCloudinary;