-
Notifications
You must be signed in to change notification settings - Fork 22
/
loadDevPortalContent.js
executable file
·627 lines (550 loc) · 17.7 KB
/
loadDevPortalContent.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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#! /usr/local/bin/node
/*jslint node:true */
// loadDevPortalContent.js
// ------------------------------------------------------------------
// load "canned" dev portal content (forum, faqs) via REST APIs.
//
// last saved: <2016-April-27 18:37:42>
var fs = require('fs'),
path = require('path'),
request = require('request'),
async = require('async'),
readlineSync = require('readline-sync'),
Getopt = require('node-getopt'),
version = '20160427-1837',
netrc = require('netrc')(),
exportDir = 'exported-' + new Date().getTime(), // ms since epoch
drupalUrl,
faqWeight = 10,
gForumsVid,
defaultContentFile = 'portalcontent.json',
getopt = new Getopt([
['S' , 'server=ARG', 'the url, including optional port and the base path (aka "endpoint")of the "services" module, of Drupal server. Eg, http://drupalserver/rest'],
['u' , 'username=ARG', 'Drupal admin user.'],
['p' , 'password=ARG', 'password for the Drupal user.'],
['n' , 'netrc', 'retrieve the username + password from the .netrc file. Use this in lieu of -u/-p'],
['c' , 'content=ARG', 'File containing portal content. Defaults to ' + defaultContentFile],
['v', 'verbose'],
['h' , 'help']
]).bindHelp();
function joinUrlElements() {
var re1 = new RegExp('^\\/|\\/$', 'g'),
elts = Array.prototype.slice.call(arguments);
return elts.map(function(element){
if ( ! element) {return '';}
return element.replace(re1,""); }).join('/');
}
function copyHash(obj) {
// shallow copy an object, looking only 1-level deep
var copy = {};
if (null !== obj && typeof obj == "object") {
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {copy[attr] = obj[attr];}
}
}
return copy;
}
function drupalLogin(cb) {
var opts = {
url : joinUrlElements(gOptions.options.server, '/user/login'),
headers : copyHash(gRequestHeaders),
body : JSON.stringify({
username : gOptions.options.username,
password : gOptions.options.password
})
};
// The x-csrf-token is documented as being required for the call to
// /user/login, but in my tests I observed that it is not actually
// required. Not for nodejs clients anyway.
//
opts.headers['content-type'] = 'application/json';
//console.log('drupalLogin opts=' + JSON.stringify(opts, null, 2));
if (gOptions.options.verbose) {
console.log('login');
}
request.post(opts,
function (error, response, body) {
var stack;
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
body = JSON.parse(body);
if ( ! (body.sessid && body.session_name && body.token)) {
cb({error: 'can\'t find valid session in response', body:body});
return;
}
if (gOptions.options.verbose) {
console.log('sess name:', body.session_name);
console.log('sess id:', body.sessid);
console.log('token:', body.token);
}
console.log('logged in as: %s %s',
body.user.field_first_name.und[0].value,
body.user.field_last_name.und[0].value);
// check for administrator role
var roles = Object.keys(body.user.roles).map(function(v){return body.user.roles[v];});
if (roles.indexOf("administrator") < 0) {
cb({error : 'not an administrator', foundroles: roles});
}
// set cookie and token globally
gRequestHeaders.cookie = body.session_name + '=' + body.sessid;
gRequestHeaders['x-csrf-token'] = body.token;
cb(null, body);
});
}
function drupalLogout(cb) {
var opts = {
url : joinUrlElements(gOptions.options.server, '/user/logout'),
headers : copyHash(gRequestHeaders),
body : ''
};
opts.headers['content-type'] = 'application/json';
if (gOptions.options.verbose) {
console.log('logout');
}
request.post(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
cb(null);
});
}
function getAllNodesOfType(type, cb) {
var opts = {
url : joinUrlElements(gOptions.options.server, '/node'),
headers : copyHash(gRequestHeaders),
qs: {pagesize: 30, 'parameters[type]': type}
};
// curl -i -X GET \
// -H Cookie:....
// -H Accept:application/json \
// 'http://server/rest/node?pagesize=30¶meters\[type\]=forum'
request.get(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
// return array of the node elements
cb(null, JSON.parse(body));
});
}
function getAllForums(cb) {
var opts = {
url : joinUrlElements(gOptions.options.server, '/taxonomy_vocabulary'),
headers : copyHash(gRequestHeaders),
qs: {pagesize: 30, 'parameters[machine_name]': 'forums'}
};
// Step 1: first get the vocabulary that corresponds to "forums":
// curl -i -X GET \
// -H Cookie:....\
// -H Accept:application/json \
// 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'
request.get(opts, function (error, response, body) {
var type;
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
body = JSON.parse(body);
type = Object.prototype.toString.call(body);
if (type !== "[object Array]" || body.length !== 1 || !body[0] || !body[0].vid) {
cb({error: 'response is not as expected'});
return;
}
// Step 2: get the terms for that vocabulary. This gives all forum names and IDs:
// curl -i -X GET \
// -H Cookie:.... \
// -H Accept:application/json \
// 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'
gForumsVid = body[0].vid;
opts.url = joinUrlElements(gOptions.options.server, '/taxonomy_term');
opts.qs = {'parameters[vid]': body[0].vid};
request.get(opts, function (error, response, body) {
var type;
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
cb(null, JSON.parse(body));
});
});
}
function deleteSingleNode(item, cb) {
// curl -i -X DELETE \
// -H Cookie:sessname=sessid \
// -H X-CSRF-Token:tokenhere \
// -H Accept:application/json \
// http://myserver/rest/node/8
var opts = {
url : item.uri,
headers : gRequestHeaders
};
if (gOptions.options.verbose) {
console.log('delete node: ' + item.title);
}
request.del(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
cb(null);
});
}
function deleteSingleForum(term, cb) {
// curl -i -X DELETE \
// -H Cookie:sessname=sessid \
// -H X-CSRF-Token:tokenhere \
// -H Accept:application/json \
// http://myserver/rest/taxonomy_term/7
var opts = {
url : joinUrlElements(gOptions.options.server, '/taxonomy_term', term.tid),
headers : gRequestHeaders
};
if (gOptions.options.verbose) {
console.log('delete forum/term: ' + term.name);
}
request.del(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
cb(null);
});
}
function createForumAndTopics(item, cb) {
var payload = {
vid : gForumsVid,
name : item.name,
description : item.description || "",
format : null,
weight : item.weight || 10
},
opts = {
url : joinUrlElements(gOptions.options.server, '/taxonomy_term'),
headers : copyHash(gRequestHeaders),
body : JSON.stringify(payload)
};
opts.headers['content-type'] = 'application/json';
// create the forum. In Drupal-speak, we are adding a new "term".
request.post(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode,
action: 'adding a term: ' + item.name});
return;
}
if (gOptions.options.verbose) {
console.log('created forum(term): ' + item.name);
}
// query to get the tid of that forum "term"
delete opts.body;
delete opts.headers['content-type'];
opts.qs = {'parameters[name]' : item.name};
request.get(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
body = JSON.parse(body);
type = Object.prototype.toString.call(body);
if (type !== "[object Array]" || body.length !== 1 || !body[0] || !body[0].tid) {
cb({error: 'response is not as expected'});
return;
}
if (item.posts && item.posts.length > 0) {
async.mapSeries(item.posts, makeForumTopicCreator(body[0].tid), function (e, deleteResponse){
if (e) {
console.log(e);
cb(e);
return;
}
if (gOptions.options.verbose) {
console.log(' all forum posts created...');
}
cb(null);
});
}
else {
cb(null);
}
});
});
}
function makeForumTopicCreator(tid) {
return function createSingleForumTopic(item, cb) {
// curl -i -X POST \
// -H Cookie:....\
// -H X-CSRF-Token:...\
// -H Accept:application/json \
// -H content-type:application/json \
// http://myserver/rest/node \
// -d '{
// "type": "forum",
// "title": "test post?",
// "language": "und",
// "taxonomy_forums": { "und": "1" },
// "body": {
// "und": [{
// "value" : "test post",
// "summary": "this is a test1",
// "format": "full_html"
// }]
// }
// }'
var payload = {
type: 'forum',
title : item.title,
language : 'und',
taxonomy_forums: { und: tid },
body: {
und: [{
value : item.text,
summary: "",
format: "full_html"
}]
}
},
opts = {
url : joinUrlElements(gOptions.options.server, '/node'),
headers : copyHash(gRequestHeaders),
body : JSON.stringify(payload)
};
opts.headers['content-type'] = 'application/json';
if (gOptions.options.verbose) {
console.log(' create topic: ' + item.title);
}
request.post(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
cb(null);
});
};
}
function createFaq(item, cb) {
var payload = {
type: 'faq',
title : item.title,
language : 'und',
status: 1,
comment: 1,
promote: 1,
weight: faqWeight,
body: {
und: [{
value : item.text,
summary: "",
format: "full_html"
}]
}
},
opts = {
url : joinUrlElements(gOptions.options.server, '/node'),
headers : copyHash(gRequestHeaders),
body : JSON.stringify(payload)
};
opts.headers['content-type'] = 'application/json';
if (gOptions.options.verbose) {
console.log(' create faq: ' + item.title);
}
request.post(opts, function (error, response, body) {
if (error) {
console.log(error);
cb(error);
return;
}
if (response.statusCode != 200) {
console.log('status: ' + response.statusCode );
cb({error: 'bad status ' + response.statusCode });
return;
}
faqWeight += 10;
cb(null);
});
}
function deleteNodesOfType(type, cb) {
getAllNodesOfType(type, function(error, result){
var r;
if (error) {
console.log('error getting %s topics: %s', type, JSON.stringify(error));
cb(error);
return;
}
r = result.map(function(item){return {uri:item.uri, title:item.title};});
async.mapSeries(r, deleteSingleNode, function (e, deleteResponse){
if (e) {
console.log('error deleting nodes: ' + JSON.stringify(e));
cb(e);
return;
}
if (gOptions.options.verbose) {
if (r.length > 0) {
console.log('all %s nodes deleted...', type);
}
else {
console.log('no %s nodes to delete...', type);
}
}
cb(null, r);
});
});
}
// ========================================================
console.log(
'Edge Dev Portal Forum Content Loader Tool, version: ' + version + '\n' +
'Node.js ' + process.version + '\n');
// process.argv array starts with 'node' and 'scriptname.js'
var gOptions = getopt.parse(process.argv.slice(2));
if (gOptions.options.netrc) {
drupalUrl = require('url').parse(gOptions.options.server);
if ( ! netrc[drupalUrl.hostname]) {
console.log('The specified host ('+ drupalUrl.hostname +') is not present in the .netrc file.');
getopt.showHelp();
process.exit(1);
}
gOptions.options.username = netrc[drupalUrl.hostname].login;
gOptions.options.password = netrc[drupalUrl.hostname].password;
}
if ( !gOptions.options.username) {
gOptions.options.username = readlineSync.question(' USER NAME : ');
}
if ( !gOptions.options.password) {
gOptions.options.password = readlineSync.question(' Password for '+gOptions.options.username + ' : ',
{hideEchoBack: true});
}
if ( !gOptions.options.username || !gOptions.options.password) {
console.log('You must provide some way to authenticate to Drupal');
getopt.showHelp();
process.exit(1);
}
if ( !gOptions.options.server) {
console.log('You must specify the Drupal server');
getopt.showHelp();
process.exit(1);
}
if ( !gOptions.options.content) {
gOptions.options.content = defaultContentFile;
}
gOptions.options.content = path.resolve('.', gOptions.options.content);
if ( ! fs.existsSync(gOptions.options.content)) {
console.log('The content file - %s - does not exist.', gOptions.options.content);
getopt.showHelp();
process.exit(1);
}
var gRequestHeaders = {
accept: 'application/json'
};
drupalLogin(function(error, result){
if (error) {
console.log('error while logging in: ' + JSON.stringify(error));
return;
}
if (gOptions.options.verbose) {
console.log('content file: ' + gOptions.options.content);
}
var content = require(gOptions.options.content);
if ( ! content.forums && !content.faqs) {
console.log('error: cannot read content file, or there is no content there...');
}
if ( ! content.forums) { content.forums = []; }
if ( ! content.faqs) { content.faqs = []; }
deleteNodesOfType('forum', function(error, result){
if (error) {
return;
}
getAllForums(function(error, result) {
if (error) {
console.log('error getting forums: ' + JSON.stringify(error));
return;
}
async.mapSeries(result, deleteSingleForum, function (e, deleteResponse){
if (e) {
console.log('while deleting forums:\n' + JSON.stringify(e, null, 2));
return;
}
async.mapSeries(content.forums, createForumAndTopics, function (e, createResponse){
if (e) {
console.log('while creating new forums:\n' + JSON.stringify(e, null, 2));
return;
}
console.log('all new forum nodes created...');
deleteNodesOfType('faq', function(error, result){
if (error) {
return;
}
async.mapSeries(content.faqs, createFaq, function (e, createResponse){
if (e) {
console.log('while creating new faqs:\n' + JSON.stringify(e, null, 2));
return;
}
console.log('all new faq nodes created...');
drupalLogout(function(error, result){ console.log('done'); });
});
});
});
});
});
});
});