This repository was archived by the owner on May 30, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathsquarespace-middleware.js
More file actions
595 lines (482 loc) · 14.3 KB
/
Copy pathsquarespace-middleware.js
File metadata and controls
595 lines (482 loc) · 14.3 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*!
*
* Squarespace Middleware.
*
*/
var _ = require( "underscore" ),
request = require( "request" ),
cookieParser = require( "cookie" ),
sqsLogger = require( "node-squarespace-logger" ),
API_AUTH_LOGIN = "/api/1/auth/Login/",
API_GET_SITELAYOUT = "/api/commondata/GetSiteLayout/",
API_GET_COLLECTIONS = "/api/commondata/GetCollections/",
API_GET_COLLECTION = "/api/commondata/GetCollection/",
API_GET_BLOCKFIELDS = "/api/block-fields/",
API_GET_WIDGETRENDERING = "/api/widget/GetWidgetRendering/";
//api/template/GetTemplateTweakSettings/
//api/template/GetTemplate?templateId=
//api/page-collection-data?collectionId=
//api/templates/:templateId
/******************************************************************************
* @Public
*******************************************************************************/
var Middleware = function () {
this.sqsUser = null;
this.sqsLoginHeaders = null;
this.sqsLoginCrumb = null;
this.config = {
siteurl: null,
sitepassword: null,
useremail: null,
userpassword: null,
sandboxmode: false,
fulldata: true
};
};
/**
*
* @method set
* @param {string} key The config key to set
* @param {string} val The config val to set
* @public
*
*/
Middleware.prototype.set = function ( key, val ) {
// If the user left a trailing slash on the siteurl, remove it.
if ( key === "siteurl" && val.charAt( val.length - 1 ) === "/" ) {
val = val.replace( /\/$/, "" );
}
this.config[ key ] = val;
};
/**
*
* @method get
* @param {string} key The config key to get value of
* @public
*
*/
Middleware.prototype.get = function ( key ) {
return this.config[ key ];
};
/**
*
* @method getCrumb
* @public
*
*/
Middleware.prototype.getCrumb = function () {
return this.sqsLoginCrumb;
};
/**
*
* @method doLogin
* @param {function} callback Fired when login and headers are set
* @public
*
*/
Middleware.prototype.doLogin = function ( callback ) {
var self = this,
cookie,
cookieParsed;
// Ensure proper config is set
if ( !this.sqsUser ) {
this.sqsUser = {
email: this.get( "useremail" ),
password: this.get( "userpassword" )
};
}
// POST to login
request({
method: "POST",
url: (this.get( "siteurl" ) + API_AUTH_LOGIN),
json: true,
headers: this.getHeaders(),
form: this.sqsUser
}, function ( error, response, json ) {
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error posting to Squarespace login with middleware => " + error) );
// Errors first
callback( error, null );
return;
}
// Request to TokenLogin
request({
url: json.targetWebsite.loginUrl,
json: true,
headers: self.getHeaders(),
qs: self.sqsUser
}, function ( error, response ) {
error = self.getError( error );
if ( error ) {
sqsLogger.log( "error", ("Error requesting secure login token from Squarespace with middleware => " + error) );
// Errors first
callback( error, null );
return;
}
// Get the response cookie we need
cookie = response.headers[ "set-cookie" ].join( ";" );
cookieParsed = cookieParser.parse( cookie );
// Set request headers we will use
headers = self.getHeaders({
"Cookie": cookie
});
// Store headers here
self.sqsLoginHeaders = headers;
// Store crumb here
self.sqsLoginCrumb = cookieParsed.crumb;
// Errors first, there are none :-)
callback( null, headers );
});
});
};
/**
*
* @method getAPICollection
* @param {string} collectionId ID of collection to get
* @param {function} callback Fired when data is fetched
* @public
*
*/
Middleware.prototype.getAPICollection = function ( collectionId, callback ) {
var self = this;
request({
url: (this.get( "siteurl" ) + API_GET_COLLECTION),
json: true,
headers: this.sqsLoginHeaders,
qs: _.extend( {collectionId: collectionId}, this.sqsUser )
}, function ( error, response, json ) {
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error requesting collection data from Squarespace with middleware => " + error) );
} else {
sqsLogger.log( "info", ("Fetched fullData for collection " + collectionId) );
callback( json );
}
});
};
/**
*
* @method getAPIData
* @param {function} callback Fired when data is fetched
* @public
*
*/
Middleware.prototype.getAPIData = function ( callback ) {
var apis = [
{
key: "siteLayout",
url: (this.get( "siteurl" ) + API_GET_SITELAYOUT)
},
{
key: "collections",
url: (this.get( "siteurl" ) + API_GET_COLLECTIONS)
}
],
data = {},
errors = [],
self = this;
function getAPI() {
var api = apis.shift();
var collections = [];
var curr = 0;
request({
url: api.url,
json: true,
headers: self.sqsLoginHeaders,
qs: self.sqsUser
}, function ( error, response, json ) {
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error fetching API data from Squarespace with middleware => " + error) );
errors.push( error );
}
// Store API data for callback
data[ api.key ] = json;
// All done, pass the API data to callback
if ( !apis.length ) {
if ( self.get( "fulldata" ) ) {
// Now get the fullData for each collection
for ( var id in data.collections.collections ) {
collections.push( data.collections.collections[ id ] );
}
collections.forEach(function ( collection ) {
self.getAPICollection( collection.id, function ( collection ) {
curr++;
data.collections.collections[ collection.id ] = collection;
if ( curr === collections.length ) {
// Errors first
callback( (errors.length ? errors : null), data );
}
});
});
} else {
// Errors first
callback( (errors.length ? errors : null), data );
}
} else {
getAPI();
}
});
}
getAPI();
};
/**
*
* @method getHtml
* @param {string} url Request url
* @param {object} qrs Querystring mapping
* @param {function} callback Fired when done
* @public
*
*/
Middleware.prototype.getHtml = function ( url, qrs, callback ) {
var self = this;
url = [this.get( "siteurl" ), url.replace( /^\/|\/$/g, "" )].join( "/" );
qrs = (qrs || {});
if ( this.get( "sitepassword" ) ) {
qrs.password = this.get( "sitepassword" );
}
// Don't allow `json` formatted requests to pass here
// But allow others, such as `main-content`
// @see: https://github.com/NodeSquarespace/node-squarespace-server/issues/128
if ( qrs.format && qrs.format.indexOf( "json" ) !== -1 ) {
delete qrs.format;
}
request({
url: url,
headers: this.getHeaders(),
qs: qrs
}, function ( error, response, html ) {
error = self.getError( error );
if ( error ) {
sqsLogger.log( "error", ("Error requesting page html from Squarespace with middleware => " + error) );
}
// Errors first
callback( error, {
html: html ? html : null,
status: response ? response.statusCode : null
});
});
};
/**
*
* @method getJson
* @param {string} url Request url
* @param {object} qrs Querystring mapping
* @param {function} callback Fired when done
* @public
*
*/
Middleware.prototype.getJson = function ( url, qrs, callback ) {
var self = this;
url = [this.get( "siteurl" ), url.replace( /^\/|\/$/g, "" )].join( "/" );
qrs = (qrs || {});
if ( this.get( "sitepassword" ) ) {
qrs.password = this.get( "sitepassword" );
}
qrs.format = "json";
request({
url: url,
json: true,
headers: this.getHeaders(),
qs: qrs
}, function ( error, response, json ) {
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error requesting page json from Squarespace with middleware => " + error) );
}
// Errors first
callback( error, {
json: json ? json : null,
status: response ? response.statusCode : null
});
});
};
/**
*
* @method getJsonAndHtml
* @param {string} url Request url
* @param {object} qrs Querystring mapping
* @param {function} callback Fired when done
* @public
*
*/
Middleware.prototype.getJsonAndHtml = function ( url, qrs, callback ) {
var res = {},
errors = [],
self = this;
this.getJson( url, qrs, function ( error, json ) {
if ( error ) {
errors.push( error );
}
res.json = json;
self.getHtml( url, qrs, function ( error, html ) {
if ( error ) {
errors.push( error );
}
res.html = html;
callback( (errors.length ? errors : null), res );
});
});
};
/**
*
* @method getQuery
* @param {object} data The hash of data a squarespace:query element supports
* @param {object} qrs Querystring mapping hash
* @param {function} callback Fired when done
* @public
*
* @data {
* collection
* category
* tag
* featured
* limit
* }
*
*/
Middleware.prototype.getQuery = function ( data, qrs, callback ) {
var url = (this.get( "siteurl" ) + "/" + data.collection + "/"),
self = this;
qrs = (qrs || {});
if ( this.get( "sitepassword" ) ) {
qrs.password = this.get( "sitepassword" );
}
qrs.format = "json";
// Tag?
if ( data.tag ) {
qrs.tag = data.tag;
}
// Category?
if ( data.category ) {
qrs.category = data.category;
}
// Request?
request({
url: url,
json: true,
headers: this.getHeaders(),
qs: qrs
}, function ( error, response, json ) {
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error requesting Squarespace:query with middleware => " + error) );
}
var items = [];
// Featured?
if ( data.featured && json.items ) {
for ( i = 0, len = json.items.length; i < len; i++ ) {
if ( json.items[ i ].starred ) {
items.push( json.items[ i ] );
}
}
json.items = items;
}
// Limit?
if ( data.limit && json.items ) {
json.items.splice( 0, (json.items.length - data.limit) );
}
// Errors first
callback( error, json );
});
};
/**
*
* @method getBlockJson
* @param {string} blockId The block id
* @param {function} callback Fired when done
* @public
*
*/
Middleware.prototype.getBlockJson = function ( blockId, callback ) {
var self = this;
request({
url: (this.get( "siteurl" ) + API_GET_BLOCKFIELDS + blockId),
json: true,
headers: this.sqsLoginHeaders,
qs: this.sqsUser
}, function ( error, response, json ) {
// Pass Error on empty block JSON
if ( !json ) {
json = { error: "Empty block JSON" };
}
error = self.getError( error, json );
// Error can come as result
if ( error ) {
sqsLogger.log( "error", ("Error requesting block json from Squarespace with middleware => " + error) );
json = null;
}
// Errors first
callback( error, json );
});
};
/**
*
* @method getWidgetHtml
* @param {object} blockJSON The block data object
* @param {function} callback Fired when done
* @public
*
*/
Middleware.prototype.getWidgetHtml = function ( blockJSON, callback ) {
var self = this;
request({
method: "POST",
url: (this.get( "siteurl" ) + API_GET_WIDGETRENDERING),
headers: this.sqsLoginHeaders,
qs: {
crumb: this.sqsLoginCrumb
},
form: {
widgetJSON: JSON.stringify( blockJSON )
//collectionId: ""
}
}, function ( error, response, string ) {
var json = JSON.parse( string.replace( /\\uFFFD/g, "" ) );
error = self.getError( error, json );
if ( error ) {
sqsLogger.log( "error", ("Error requesting widget html from Squarespace with middleware => " + error) );
json = null;
}
// Errors first
callback( error, json );
});
};
/**
*
* @method getError
* @description Normalize error handling based on Squarespace's responses
* @private
*
*/
Middleware.prototype.getError = function ( error, json ) {
return (typeof json === "object" && json.error ? json.error : error);
};
/**
*
* @method getHeaders
* @param {object} headers Merge object with required headers
* @returns {object}
* @private
*
*/
Middleware.prototype.getHeaders = function ( headers ) {
var ret = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"
};
if ( headers ) {
ret = _.extend( ret, headers );
}
if ( this.sqsLoginHeaders ) {
ret = _.extend( ret, this.sqsLoginHeaders );
}
return ret;
};
/******************************************************************************
* @Export
*******************************************************************************/
module.exports = {
Middleware: Middleware
};