/
create-local-file-node.js
373 lines (311 loc) · 10 KB
/
create-local-file-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
import fs from "fs-extra"
import path from "path"
import url from "url"
import { bold } from "chalk"
import retry from "async-retry"
import { createFileNodeFromBuffer } from "gatsby-source-filesystem"
import createRemoteFileNode from "./create-remote-file-node/index"
import store from "~/store"
import urlToPath from "~/utils/url-to-path"
import { formatLogMessage } from "~/utils/format-log-message"
import { stripImageSizesFromUrl } from "~/steps/source-nodes/fetch-nodes/fetch-referenced-media-items"
import { ensureSrcHasHostname } from "./process-node"
export const getFileNodeMetaBySourceUrl = sourceUrl => {
const fileNodesMetaByUrls = store.getState().imageNodes.nodeMetaByUrl
return fileNodesMetaByUrls[stripImageSizesFromUrl(sourceUrl)]
}
export const getMediaItemEditLink = node => {
const { helpers, pluginOptions } = store.getState().gatsbyApi
const { protocol, hostname } = url.parse(node?.link || pluginOptions.url)
const baseUrl = `${protocol}//${hostname}`
const databaseId = node.databaseId
if (!databaseId) {
const parentNode = node.parentHtmlNode || helpers.getNode(node.id)
if (!parentNode?.databaseId) {
return null
}
return `${baseUrl}/wp-admin/post.php?post=${parentNode.databaseId}&action=edit`
}
return `${baseUrl}/wp-admin/upload.php?item=${node.databaseId}`
}
export const errorPanicker = ({
error,
reporter,
node,
fetchState,
parentName,
}) => {
const editUrl = getMediaItemEditLink(node)
const stepMessage = parentName ? ` in step:\n\n"${parentName}"` : ``
const mediaItemLink = node.link ? `\nMedia item link: ${node.link}` : ``
const editLink = `\nEdit link: ${editUrl || `N/A`}`
const fileUrl = `\nFile url: ${node.mediaItemUrl}`
const sharedError = `occurred while fetching media item${
node.databaseId ? ` #${node.databaseId}` : ``
}${stepMessage}\n${mediaItemLink}${editLink}${fileUrl}`
const errorString =
typeof error === `string` ? error : error && error.toString()
const { pluginOptions } = store.getState().gatsbyApi
const allow404ImagesInProduction = pluginOptions.production.allow404Images
const allow401ImagesInProduction = pluginOptions.production.allow401Images
const errorCodeIs404 = errorString.includes(`Response code 404`)
const errorCodeIs401 = errorString.includes(`Response code 401`)
const errorCode = errorCodeIs404 ? `404` : errorCodeIs401 ? `401` : null
if (
(allow404ImagesInProduction ||
allow401ImagesInProduction ||
process.env.NODE_ENV !== `production`) &&
(errorCodeIs404 || errorCodeIs401)
) {
fetchState.shouldBail = true
reporter.log(``)
reporter.warn(
formatLogMessage(
`Error ${sharedError}${
!allow404ImagesInProduction || !allow401ImagesInProduction
? `\n\nThis error will fail production builds.`
: ``
}`
)
)
reporter.log(``)
return
}
if (errorString.includes(`Response code 4`)) {
reporter.log(``)
reporter.info(
formatLogMessage(
`Unrecoverable error ${sharedError}\n\nFailing the build to prevent deploying a broken site.${
errorCode
? `\n\nIf you don't want ${errorCode}'s to fail your production builds, you can set the following option:
{
options: {
production: {
allow${errorCode}Images: true
}
}
}`
: ``
}`
)
)
reporter.panic(error)
} else if (errorString.includes(`Response code 5`)) {
reporter.log(``)
reporter.info(
formatLogMessage(
[
`Unrecoverable error ${sharedError}`,
`\nYour wordpress host appears to be overloaded by our requests for images`,
`\nIn ${bold(`gatsby-config.js`)}, try lowering the ${bold(
`requestConcurrency`
)} for MediaItems:`,
`\nplugins: [
{
resolve: 'gatsby-source-wordpress',
options: {
url: 'https://mysite.com/graphql',
type: {
MediaItem: {
localFile: {
requestConcurrency: 50
}
}
}
},
}
]`,
`\nnote that GATSBY_CONCURRENT_REQUEST environment variable has been retired for these options`,
].join(`\n`)
)
)
reporter.panic(error)
} else {
console.error(error)
reporter.panic()
}
}
export const getFileNodeByMediaItemNode = async ({
mediaItemNode,
helpers,
}) => {
const { sourceUrl, modifiedGmt, mediaItemUrl, databaseId } = mediaItemNode
const fileUrl = sourceUrl || mediaItemUrl
if (!fileUrl) {
helpers.reporter.warn(
formatLogMessage(`Couldn't find source url for media item #${databaseId}`)
)
return null
}
const existingNodeMeta = getFileNodeMetaBySourceUrl(fileUrl)
if (
// if we already have this image
existingNodeMeta &&
existingNodeMeta.id &&
// and it hasn't been modified
existingNodeMeta.modifiedGmt === modifiedGmt
) {
let node = await helpers.getNode(existingNodeMeta.id)
// some of the cached node metas don't necessarily need to be a File
// so make sure we return a File node if what we get isn't one
if (node && node.internal && node.internal.type !== `File`) {
if (node.localFile && node.localFile.id) {
// look up the corresponding file node
node = await helpers.getNode(node.localFile.id)
} else {
return null
}
}
return node
}
return null
}
const failedImageUrls = new Set()
export const createLocalFileNode = async ({
mediaItemNode,
parentName,
skipExistingNode = false,
}) => {
const state = store.getState()
const { helpers, pluginOptions } = state.gatsbyApi
const existingNode = !skipExistingNode
? await getFileNodeByMediaItemNode({
mediaItemNode,
helpers,
})
: null
if (existingNode) {
return existingNode
}
const {
store: gatsbyStore,
cache,
createNodeId,
reporter,
actions: { createNode },
} = helpers
let { mediaItemUrl, modifiedGmt, mimeType, title, fileSize } = mediaItemNode
if (!mediaItemUrl || failedImageUrls.has(mediaItemUrl)) {
return null
}
const { wpUrl } = state.remoteSchema
mediaItemUrl = ensureSrcHasHostname({ wpUrl, src: mediaItemUrl })
const { excludeByMimeTypes, maxFileSizeBytes } =
// eslint-disable-next-line no-unsafe-optional-chaining
pluginOptions.type?.MediaItem?.localFile
// if this file is larger than maxFileSizeBytes, don't fetch the remote file
if (fileSize > maxFileSizeBytes) {
store.dispatch.postBuildWarningCounts.incrementMaxFileSizeBytesExceeded()
return null
}
// if this type of file is excluded, don't fetch the remote file
if (excludeByMimeTypes.includes(mimeType)) {
store.dispatch.postBuildWarningCounts.incrementMimeTypeExceeded()
return null
}
const hardCachedFileRelativePath = urlToPath(mediaItemUrl)
const hardCachedMediaFilesDirectory = `${process.cwd()}/.wordpress-cache`
const hardCachedFilePath =
hardCachedMediaFilesDirectory + hardCachedFileRelativePath
const hardCacheMediaFiles =
(process.env.NODE_ENV === `development` &&
pluginOptions.develop.hardCacheMediaFiles) ||
(process.env.NODE_ENV === `production` &&
pluginOptions.production.hardCacheMediaFiles)
const fetchState = {
shouldBail: false,
}
const createFileNodeRequirements = {
parentNodeId: mediaItemNode.id,
store: gatsbyStore,
cache,
createNode,
createNodeId,
}
let remoteFileNode
if (hardCacheMediaFiles) {
// check for file in .wordpress-cache/wp-content
// if it exists, use that to create a node from instead of
// fetching from wp
try {
const buffer = await fs.readFile(hardCachedFilePath)
remoteFileNode = await createFileNodeFromBuffer({
buffer,
name: title,
ext: path.extname(mediaItemUrl),
...createFileNodeRequirements,
})
} catch (e) {
// ignore errors, we'll download the image below if it doesn't exist
}
}
if (!remoteFileNode) {
// Otherwise we need to download it
remoteFileNode = await retry(
async () => {
if (fetchState.shouldBail) {
failedImageUrls.add(mediaItemUrl)
return null
}
const { hostname: wpUrlHostname } = url.parse(wpUrl)
const { hostname: mediaItemHostname } = url.parse(mediaItemUrl)
const htaccessCredentials = pluginOptions.auth.htaccess
// if media items are hosted on another url like s3,
// using the htaccess creds will throw 400 errors
const shouldUseHtaccessCredentials = wpUrlHostname === mediaItemHostname
const auth =
htaccessCredentials && shouldUseHtaccessCredentials
? {
htaccess_pass: htaccessCredentials?.password,
htaccess_user: htaccessCredentials?.username,
}
: null
// if this errors, it's caught one level above in fetch-referenced-media-items.js so it can be placed on the end of the request queue
const node = await createRemoteFileNode({
url: mediaItemUrl,
auth,
...createFileNodeRequirements,
reporter,
pluginOptions,
})
return node
},
{
retries: 3,
factor: 1.1,
minTimeout: 5000,
onRetry: error =>
errorPanicker({
error,
reporter,
node: mediaItemNode,
fetchState,
parentName,
}),
}
)
}
if (!remoteFileNode) {
return null
}
// push it's id and url to our store for caching,
// so we can touch this node next time
// and so we can easily access the id by source url later
store.dispatch.imageNodes.pushNodeMeta({
id: remoteFileNode.id,
sourceUrl: mediaItemUrl,
modifiedGmt,
})
if (hardCacheMediaFiles) {
try {
// make sure the directory exists
await fs.ensureDir(path.dirname(hardCachedFilePath))
// copy our downloaded file to our existing directory
await fs.copyFile(remoteFileNode.absolutePath, hardCachedFilePath)
} catch (e) {
helpers.reporter.panic(e)
}
}
// and use it
return remoteFileNode
}