-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.ts
262 lines (254 loc) Β· 5.9 KB
/
gatsby-node.ts
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
import path from 'path';
import fs from 'fs';
import { createFilePath } from 'gatsby-source-filesystem';
import webvtt from 'node-webvtt';
import { GatsbyNode } from 'gatsby';
import mm from 'music-metadata'; // NOTE: ver 7 last which works without module changes
const hasPage = (
edge: Queries.createPagesInNodeQuery['allMarkdownRemark']['edges'][number]
) => {
if (edge.node?.fields?.sourceInstanceName) {
switch (edge.node.fields.sourceInstanceName) {
case 'misc': {
return false;
break;
}
case 'footerMenus': {
return false;
break;
}
}
return true;
}
return false;
};
const constructPrevNextObject = (
post: Queries.createPagesInNodeQuery['allMarkdownRemark']['edges'][number]
) => {
if (post.node.frontmatter?.title && post.node.fields?.slug) {
return {
title: post.node.frontmatter.title,
slug: post.node.fields.slug,
};
} else {
return {};
}
};
const findPrev = (
posts: Queries.createPagesInNodeQuery['allMarkdownRemark']['edges'],
startIndex: number,
sourceInstanceName: string | null
) => {
let i = startIndex - 1;
while (i >= 0) {
const post = posts[i];
if (
post.node.fields?.sourceInstanceName &&
post.node.fields.sourceInstanceName === sourceInstanceName &&
hasPage(post)
) {
return constructPrevNextObject(post);
}
i--;
}
return null;
};
const findNext = (
posts: Queries.createPagesInNodeQuery['allMarkdownRemark']['edges'],
startIndex: number,
sourceInstanceName: string | null
) => {
let i = startIndex + 1;
while (i < posts.length) {
const post = posts[i];
if (
post.node.fields?.sourceInstanceName &&
post.node.fields.sourceInstanceName === sourceInstanceName &&
hasPage(post)
) {
return constructPrevNextObject(post);
}
i++;
}
return null;
};
const parseSubtitles = (subsFile: fs.PathOrFileDescriptor) => {
const input = fs.readFileSync(subsFile).toString();
const parsed = webvtt.parse(input);
if (parsed.valid) {
const { cues } = parsed;
return cues.map((cue) => ({
text: cue.text.replace(/(<([^>]+)>)/gi, ''), // remove speaker tags
startTime: cue.start,
endTime: cue.end,
}));
} else {
console.error('Error parsing subtitles:', parsed.errors);
return [];
}
};
const parseAudioFile = async (audioFile: string) => {
try {
const metadata = await mm.parseFile(audioFile, {
duration: true,
skipCovers: true,
});
const durationSeconds = metadata?.format?.duration;
if (durationSeconds) {
const durationFloat =
typeof durationSeconds === 'string'
? parseFloat(durationSeconds)
: durationSeconds;
const durationString = new Date(1000 * durationFloat)
.toISOString()
.substring(11, 19); // Will break at 25 hours
return { durationSeconds, durationString };
}
} catch (error) {
console.error('Error parsing audio file:', error);
}
return { durationSeconds: 0, durationString: '00:00:00' };
};
export const createPages: GatsbyNode['createPages'] = async ({
actions,
graphql,
}) => {
const { createPage } = actions;
const result = await graphql<Queries.createPagesInNodeQuery>(`
query createPagesInNode {
allMarkdownRemark(
sort: { frontmatter: { date: ASC } }
limit: 10000
) {
edges {
node {
id
fields {
slug
sourceInstanceName
}
frontmatter {
title
subtitles {
absolutePath
}
audioFile {
absolutePath
}
}
rawMarkdownBody
}
}
}
}
`);
if (result.errors) {
if (Array.isArray(result.errors)) {
result?.errors.forEach((e) =>
console.error((e as string).toString())
);
}
return Promise.reject(result.errors);
}
const posts = result?.data?.allMarkdownRemark.edges;
if (posts && posts.length > 0) {
posts.forEach((edge, index, array) => {
const id = edge.node.id;
if (hasPage(edge)) {
const { sourceInstanceName } = edge.node.fields as {
sourceInstanceName: string;
};
const context = {
id,
next: findNext(array, index, sourceInstanceName),
prev: findPrev(array, index, sourceInstanceName),
} as {
id: string;
next:
| {
title: string;
slug: string;
}
| {
title?: undefined;
slug?: undefined;
}
| null;
prev:
| {
title: string;
slug: string;
}
| {
title?: undefined;
slug?: undefined;
}
| null;
subtitlesArray?: Array<{
text: string;
startTime: number;
endTime: number;
}>;
};
if (sourceInstanceName === 'episodes') {
const subsFile = edge?.node?.frontmatter?.subtitles
?.absolutePath as string;
context.subtitlesArray = parseSubtitles(subsFile);
}
createPage({
path: edge?.node?.fields?.slug as string,
component: path.resolve(
`src/templates/${String(sourceInstanceName)}.tsx`
),
// additional data can be passed via context
context,
});
}
});
}
};
export const onCreateNode: GatsbyNode['onCreateNode'] = async ({
node,
actions,
getNode,
}) => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark') {
const { sourceInstanceName } = getNode(node.parent as string) as Record<
string,
string
>;
const relativePath = createFilePath({
node,
getNode,
trailingSlash: false,
});
createNodeField({
name: 'slug',
node,
value: `/${sourceInstanceName}${relativePath}`,
});
createNodeField({
name: 'sourceInstanceName',
node,
value: sourceInstanceName,
});
} else if (
node.internal.type === 'File' &&
node?.sourceInstanceName === 'episodes' &&
node?.internal?.mediaType &&
node?.internal?.mediaType.includes('audio')
) {
const audioData = await parseAudioFile(node.absolutePath as string);
createNodeField({
name: 'durationSeconds',
node,
value: audioData.durationSeconds,
});
createNodeField({
name: 'durationString',
node,
value: audioData.durationString,
});
}
};