-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgatsby-node.js
597 lines (523 loc) Β· 19.1 KB
/
gatsby-node.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
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const { execSync } = require('child_process');
const showdown = require('showdown');
const algoliasearch = require('algoliasearch');
const striptags = require('striptags');
const RSS = require('rss');
const config = require('./config');
const constants = require('./src/contants');
const buildProvisioning = require('./src/builder/provisioning');
const markdownConverter = new showdown.Converter();
const overviews = {};
const corporate = !!process.env.CORPORATE;
const siteUrl = corporate ? 'http://developers.wazo.io' : 'https://wazo-platform.org';
const siteTitle = 'Wazo Platform Blog';
let hasSearch = config.algolia && !!config.algolia.appId && !!config.algolia.apiKey;
let algoliaIndex = null;
if (hasSearch) {
console.info('Enabling Algolia search');
const algoliaClient = algoliasearch(config.algolia.appId, config.algolia.apiKey);
const algoliaKeyIndex = corporate ? constants.algoliaIndexDeveloper : constants.algoliaIndexPlatform;
algoliaIndex = algoliaClient.initIndex(algoliaKeyIndex);
algoliaIndex.setSettings(
{
attributeForDistinct: 'title',
attributesToHighlight: ['title', 'content'],
attributesToSnippet: ['content'],
distinct: true,
},
(err) => {
if (err) {
hasSearch = false;
console.error('Algolia error:' + err.message);
}
}
);
}
const walk = (dir) => {
const files = fs.readdirSync(dir);
const dirname = dir.split('/').pop();
console.info('processing ' + dir);
files.forEach((file) => {
const filePath = dir + '/' + file;
if (fs.statSync(filePath).isDirectory()) {
walk(filePath);
} else if (file === 'description.md') {
overviews[dirname] = fs.readFileSync(filePath, 'utf8');
}
});
};
const getArticles = async (graphql, newPageRef) => {
console.info('generating articles');
const articlesResponses = await graphql(`
{
allMarkdownRemark(
filter: {
fileAbsolutePath: { regex: "/blog/" },
frontmatter: { status: { eq: "published" } }
}
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
id
fileAbsolutePath
frontmatter {
author
category
date(formatString: "DD MMMM YYYY")
slug
status
tags
title
}
html
algoliaContent: excerpt(format: PLAIN, pruneLength: 10000)
summary: excerpt(format: PLAIN, pruneLength: 250, truncate: true)
}
}
}
}
`);
// Handle errors
if (articlesResponses.errors) {
reporter.panicOnBuild(`Error while running "blog articles" GraphQL query.`);
return;
}
const articles = [];
var rssFeed = new RSS({
title: siteTitle,
description: 'Wazo Platform - An Open Source project to build your own IP telecom platform.',
language: 'en',
image_url: `${siteUrl}/images/og-image.jpg`,
feed_url: `${siteUrl}/rss.xml`,
site_url: `${siteUrl}/`,
});
articlesResponses.data.allMarkdownRemark.edges.forEach(({ node }) => {
const options = {
summary: node.summary,
...node.frontmatter,
}
const blogPath = `/blog/${options.slug}`;
console.info(`- generating article: ${blogPath}`);
articles.push(options);
const articleContext = {
...options,
content: node.html,
description: node.summary,
algoliaContent: node.algoliaContent,
};
newPageRef(blogPath, 'blog/article', articleContext);
rssFeed.item({
title: options.title,
description: options.summary + '...',
url: `${siteUrl}${blogPath}`,
author: options.author,
categories: [options.category],
date: options.date.indexOf(':') !== -1 ? options.date : `${options.date} 14:00:00`,
enclosure: {
url: `${siteUrl}/images/og-image.jpg`, // @todo change image, change when og:image per article
},
});
});
console.log('generating articles rss feed');
fs.writeFile(__dirname + '/public/rss.xml', rssFeed.xml({ indent: true }), (err) => {
if (err) console.log(err);
});
return articles;
};
const getTutorials = async (graphql, newPageRef) => {
console.info('generating tutorials');
const tutorialsResponse = await graphql(`
{
allMarkdownRemark(
filter: {
fileAbsolutePath: { regex: "/tutorials/" },
frontmatter: { status: { eq: "published" } }
}
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
id
fileAbsolutePath
frontmatter {
author
category
date(formatString: "DD MMMM YYYY")
slug
status
tags
title
ogimage
thumbnail
}
html
algoliaContent: excerpt(format: PLAIN, pruneLength: 10000)
summary: excerpt(format: PLAIN, pruneLength: 250, truncate: true)
}
}
}
}
`);
// Handle errors
if (tutorialsResponse.errors) {
reporter.panicOnBuild(`Error while running "tutorials" GraphQL query.`);
return;
}
const tutorials = [];
// files.forEach((file, key) => {
tutorialsResponse.data.allMarkdownRemark.edges.forEach(({ node }) => {
const options = {
summary: node.summary,
...node.frontmatter,
}
const tutorialPath = `/tutorials/${options.slug}`;
console.info(`- generating tutorial: ${tutorialPath}`);
tutorials.push(options);
const tutorialContext = {
...options,
content: node.html,
description: options.summary,
algoliaContent: node.algoliaContent,
};
newPageRef(tutorialPath, 'tutorials/tutorial', tutorialContext);
});
return tutorials;
};
const walk_md_files = (dir, path, acc, index) => {
const files = fs.readdirSync(dir);
console.info('scanning dir ' + dir);
files.forEach((file) => {
const filePath = dir + '/' + file;
if (fs.statSync(filePath).isDirectory()) {
if (file !== '.') {
walk_md_files(filePath, path + file + '/', acc, index);
}
} else if (file === index) {
console.info('storing index ' + path);
acc[path] = fs.readFileSync(filePath, 'utf8');
} else {
const names = file.split('.');
const ext = names.pop();
const fname = names.pop();
if (ext === 'md') {
const p = path + fname;
console.info('storing ' + p);
acc[p] = fs.readFileSync(filePath, 'utf8');
}
}
});
return acc;
};
exports.createPages = async ({ graphql, actions: { createPage, createRedirect } }) => {
console.log(`Building ${corporate ? 'developers.wazo.io' : 'wazo-platform.org'}`);
try {
fs.writeFile('config-wazo.js', `export const corporate = ${corporate ? 'true' : 'false'};`, () => null);
} catch (e) {
console.error(e);
}
// Init algolia index
if (hasSearch) {
await new Promise((resolve) => algoliaIndex.clearIndex(resolve));
}
const ecosystemDoc = fs.readFileSync('./content/ecosystem.md', 'utf8');
const installDoc = fs.readFileSync('./content/use-cases.md', 'utf8');
const installC4Doc = fs.readFileSync('./content/install-c4.md', 'utf8');
const contributeDoc = fs.readFileSync('./content/contribute.md', 'utf8');
const rawSections = yaml.load(fs.readFileSync('./content/sections.yaml', { encoding: 'utf-8' }));
// when CORPORATE is set do not filter section, otherwise only display what is not for developer
const sections = rawSections.filter((section) => (!corporate ? !section.corporate : true));
const contributeDocs = walk_md_files('content/contribute', '', {}, 'description.md');
const allModules = sections.reduce((acc, section) => {
Object.keys(section.modules).forEach((moduleName) => (acc[moduleName] = section.modules[moduleName]));
return acc;
}, {});
var algoliaObjects = [];
const getModuleName = (repoName) =>
Object.keys(allModules).find((moduleName) => {
const { repository } = allModules[moduleName];
return repository && repoName === repository.replace('wazo-', '');
});
// Helper to generate page
const newPage = (pagePath, component, context) => {
createPage({
path: pagePath,
component: path.resolve(`src/component/${component}.js`),
context,
});
if (hasSearch && component !== '404') {
const title = context ? (context.module ? context.module.title : context.title) : null;
const description = context ? (context.module ? context.module.description : context.description) : null;
if (!title) {
return;
}
// Remove pagePath starting with a slash, causing issue with algolia
let searchPagePath = pagePath;
if (searchPagePath.indexOf('/') === 0) {
searchPagePath = pagePath.substring(1);
}
algoliaObjects.push({
title,
description,
content: context && context.algoliaContent ? context.algoliaContent : null,
pagePath: searchPagePath,
});
}
};
// Retrieve all diagrams
const diagramOutputDir = path.resolve('public/diagrams/');
walk('content');
// Generate puml to svg
console.info(`generating svg diagrams in ${diagramOutputDir}...`);
try {
execSync(`make plantuml-diagrams DIAGRAM_DIRECTORY=${diagramOutputDir}`);
} catch (e) {
console.error('error generating diagrams', e);
}
console.info(`done generating svg diagrams`);
// Create homepage
await newPage('/', corporate ? 'corporate/index' : 'home/index', corporate ? { sections, overviews } : null);
if (!corporate) {
// Create doc page
await newPage('/documentation', 'documentation/index', { sections, overviews });
// Create install page
await newPage('/use-cases', 'use-cases/index', { installDoc });
// Create install-c4 page
await newPage('/use-cases/class-4', 'install_c4/index', { installC4Doc });
// Create contribute page
await newPage('/contribute', 'contribute/index', { content: contributeDoc });
// Create blog page
const articles = await getArticles(graphql, newPage);
await newPage('/blog', 'blog/index', { articles });
// Create tutorials page
const tutorials = await getTutorials(graphql, newPage);
await newPage('/tutorials', 'tutorials/index', { tutorials });
// Create ecosystem page
await newPage('/ecosystem', 'ecosystem/index', { content: ecosystemDoc });
// Create contribute pages
Object.keys(contributeDocs).forEach((fileName) => {
const rawContent = contributeDocs[fileName].split('\n');
const title = rawContent[0];
rawContent.shift();
rawContent.shift();
const content = rawContent.join('\n');
var p = '/contribute/' + path.basename(fileName, '.md');
console.log('generating ' + p);
newPage(p, 'contribute/index', { content, title });
});
// Create uc-doc pages
// ---------
const ucDocsResponse = await graphql(`
{
allMarkdownRemark(
filter: { fileAbsolutePath: { regex: "/uc-doc/" } }
sort: { fields: [frontmatter___title], order: ASC }
) {
edges {
node {
id
fileAbsolutePath
frontmatter {
title
subtitle
}
html
algoliaContent: excerpt(pruneLength: 800)
description: excerpt(pruneLength: 200)
}
}
}
}
`);
// Handle errors
if (ucDocsResponse.errors) {
reporter.panicOnBuild(`Error while running UC-DOC GraphQL query.`);
return;
}
let dynamicUcDocMenu = {};
ucDocsResponse.data.allMarkdownRemark.edges.forEach(({ node }) => {
const pagePath = node.fileAbsolutePath.split('content/')[1].split('.')[0].replace('index', '');
newPage(pagePath, 'uc-doc/index', {
content: node.html,
title: node.frontmatter.title,
algoliaContent: node.algoliaContent,
pagePath,
});
// Generate json file to make a dynamic submenu in /uc-doc
const pathSteps = pagePath.split('/').filter((step) => step !== '');
dynamicUcDocMenu = pathSteps.reduce((acc, val, index) => {
let depthCursor = acc;
for (var i = 0; i < index; i++) {
depthCursor = depthCursor[pathSteps[i]];
}
if (!depthCursor[val]) {
depthCursor[val] = {};
}
if (pathSteps.length - 1 === index) {
depthCursor[val].self = {
title: node.frontmatter.title,
path: `/${pagePath}`,
};
}
return acc;
}, dynamicUcDocMenu);
});
// custom patch to provisioning
dynamicUcDocMenu['uc-doc'].ecosystem.supported_devices = {
self: {
title: 'Supported Devices',
path: '/uc-doc/ecosystem/supported_devices',
},
};
const jsonFolder = `${__dirname}/public/json`;
if (!fs.existsSync(jsonFolder)) {
fs.mkdirSync(jsonFolder);
}
fs.writeFile(`${jsonFolder}/uc-doc-submenu.json`, JSON.stringify(dynamicUcDocMenu), (err) => {
if (err) console.log(err);
});
}
// Create api pages
// ----------
sections.forEach((section) =>
Object.keys(section.modules).forEach((moduleName) =>
newPage(`/documentation/api/${moduleName}.html`, 'documentation/api', {
moduleName,
module: section.modules[moduleName],
})
)
);
// Create console pages
sections.forEach((section) =>
Object.keys(section.modules).forEach(
(moduleName) =>
!!section.modules[moduleName].redocUrl &&
newPage(`/documentation/console/${moduleName}`, 'documentation/console', {
moduleName,
module: section.modules[moduleName],
modules: section.modules,
auth_url: !section.modules[moduleName].corporate
? allModules['authentication'].redocUrl
: section.modules['euc-authentication'].redocUrl,
})
)
);
// Create async-ap pages
sections.forEach((section) =>
Object.keys(section.modules).forEach(
(moduleName) =>
!!section.modules[moduleName].redocUrl &&
newPage(`/documentation/events/${moduleName}`, 'documentation/async-api', {
moduleName,
module: section.modules[moduleName],
modules: section.modules,
auth_url: !section.modules[moduleName].corporate
? allModules['authentication'].redocUrl
: section.modules['euc-authentication'].redocUrl,
})
)
);
// integrate graphiql @TEMP: restricting to 'contact'... for now i hope :)
sections.forEach((section) =>
Object.keys(section.modules).forEach(
(moduleName) =>
!!section.modules[moduleName].graphql &&
newPage(`/documentation/graphql/${moduleName}`, 'documentation/graphql', {
moduleName,
module: section.modules[moduleName],
modules: section.modules,
})
)
);
// Create overview and extra pages
Object.keys(allModules).forEach((moduleName) => {
const module = allModules[moduleName];
const repoName = module.repository;
if (!repoName) {
return;
}
newPage(`/documentation/overview/${moduleName}.html`, 'documentation/overview', {
overview: overviews[repoName.replace('wazo-', '')],
moduleName,
module,
});
const dir = 'content/' + repoName.replace('wazo-', '');
const files = fs.existsSync(dir) ? fs.readdirSync(dir) : [];
files.forEach((file, key) => {
if (file.endsWith('.md') && file != 'description.md') {
const filePath = `${dir}/${file}`;
const baseName = file.replace('.md', '');
const content = fs.readFileSync(filePath, 'utf8');
console.log(`generating /documentation/overview/${moduleName}-${baseName}.html`);
newPage(`/documentation/overview/${moduleName}-${baseName}.html`, 'documentation/overview', {
overview: content,
moduleName,
module,
});
}
});
});
console.info('Building provisioning...');
await buildProvisioning(newPage);
// Update algolia index
if (hasSearch) {
algoliaIndex.addObjects(algoliaObjects);
}
// Generate redirect 301
// ---------
console.log('Generating 301 redirects');
const generate301 = (fromPath, toPath) => {
const enhancedFromPath = fromPath.endsWith('.html') || fromPath.endsWith('/') ? fromPath : `${fromPath}/`
createRedirect({
fromPath: enhancedFromPath,
isPermanent: true,
redirectInBrowser: true,
toPath,
});
}
if (corporate) {
['/api/nestbox-deployd.html', '/documentation/api/nestbox-deployd.html'].forEach((fromPath) => {
generate301(fromPath, '/documentation/api/euc-deployd.html');
});
['/api/nestbox-configuration.html', '/documentation/api/nestbox-configuration.html'].forEach((fromPath) => {
generate301(fromPath, '/documentation/api/euc-configuration.html');
});
['/api/nestbox-authentication.html', '/documentation/api/nestbox-authentication.html'].forEach((fromPath) => {
generate301(fromPath, '/documentation/api/euc-authentication.html');
});
}
generate301('/uc-doc/administration/contact_directories/general', '/uc-doc/administration/contact_directories');
generate301('/uc-doc/administration/interconnections/introduction', '/uc-doc/administration/interconnections');
generate301('/uc-doc/administration/provisioning/introduction', '/uc-doc/administration/provisioning');
generate301('/uc-doc/administration/users/users', '/uc-doc/administration/users');
generate301('/uc-doc/api_sdk/mobile/push_notification', '/uc-doc/api_sdk/mobile_push_notification');
generate301('/uc-doc/api_sdk/mobile', '/uc-doc/api_sdk/mobile_push_notification');
generate301('/uc-doc/contact_center/introduction', '/uc-doc/contact_center');
generate301('/uc-doc/high_availability/introduction', '/uc-doc/high_availability');
generate301('/uc-doc/installation/install-system', '/uc-doc/installation');
generate301('/uc-doc/upgrade/introduction', '/uc-doc/upgrade');
generate301('/uc-doc/upgrade/upgrade_specific_version/introduction', '/uc-doc/upgrade/upgrade_specific_version');
generate301('/uc-doc/system/wazo-auth/introduction', '/uc-doc/system/wazo-auth');
generate301('/uc-doc/system/wazo-confd/introduction', '/uc-doc/system/wazo-confd');
generate301('/uc-doc/system/wazo-confgend/introduction', '/uc-doc/system/wazo-confgend');
generate301('/uc-doc/system/wazo-dird/introduction', '/uc-doc/system/wazo-dird');
generate301('/uc-doc/introduction', '/uc-doc');
generate301('/uc-doc/changelog', '/uc-doc');
generate301('/uc-doc/upgrade/old_upgrade_notes', '/uc-doc/upgrade/archives/upgrade_notes');
generate301('/uc-doc/upgrade/upgrade_from_wazo_18_03', '/uc-doc/upgrade/archives/upgrade_from_wazo_18_03');
generate301('/uc-doc/upgrade/migrate_i386_to_amd64', '/uc-doc/upgrade/archives/migrate_i386_to_amd64');
};
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
alias: {
mainCSS: !!process.env.CORPORATE
? path.resolve(__dirname, 'src/styles/corporate')
: path.resolve(__dirname, 'src/styles/platform'),
},
},
});
};