@@ -3,10 +3,18 @@ const got = require(`got`)
33const crypto = require ( `crypto` )
44const path = require ( `path` )
55const { isWebUri } = require ( `valid-url` )
6+ const mime = require ( `mime` )
7+ const readChunk = require ( `read-chunk` )
8+ const fileType = require ( `file-type` )
69
710const { createFileNode } = require ( `./create-file-node` )
811const cacheId = url => `create-remote-file-node-${ url } `
912
13+ const getUrlWithoutQuery = url => {
14+ const pos = url . indexOf ( `?` )
15+ return url . substring ( 0 , pos != - 1 ? pos : url . length )
16+ }
17+
1018module . exports = ( { url, store, cache, createNode } ) =>
1119 new Promise ( async ( resolve , reject ) => {
1220 if ( ! url || isWebUri ( url ) === undefined ) {
@@ -36,17 +44,22 @@ module.exports = ({ url, store, cache, createNode }) =>
3644 . createHash ( `md5` )
3745 . update ( url )
3846 . digest ( `hex` )
47+
48+ // Question mark and ampersand are illegal filename characters. Strip
49+ // GET query and question mark seperator from url. To get extension
50+ // with allowed characters.
51+ const urlWithoutQuery = getUrlWithoutQuery ( url )
3952 const tmpFilename = path . join (
4053 store . getState ( ) . program . directory ,
4154 `.cache` ,
4255 `gatsby-source-filesystem` ,
43- `tmp-` + digest + path . parse ( url ) . ext
56+ `tmp-` + digest + path . parse ( urlWithoutQuery ) . ext
4457 )
45- const filename = path . join (
58+ let filename = path . join (
4659 store . getState ( ) . program . directory ,
4760 `.cache` ,
4861 `gatsby-source-filesystem` ,
49- digest + path . parse ( url ) . ext
62+ digest + path . parse ( urlWithoutQuery ) . ext
5063 )
5164
5265 // Fetch the file.
@@ -77,6 +90,22 @@ module.exports = ({ url, store, cache, createNode }) =>
7790 // Save the response headers for future requests.
7891 cache . set ( cacheId ( url ) , responseHeaders )
7992 if ( statusCode === 200 ) {
93+ const mimeTypeFromExtension = mime . lookup ( tmpFilename )
94+ if ( mimeTypeFromExtension === `application/octet-stream` ) {
95+ // MIME type from extension not found
96+ // (https://github.com/broofa/node-mime/tree/v1.4.0).
97+ // Let's try detect MIME type by checking magic number
98+ const buffer = readChunk . sync ( tmpFilename , 0 , 4100 )
99+ const type = fileType ( buffer )
100+ if ( type ) {
101+ filename = path . join (
102+ store . getState ( ) . program . directory ,
103+ `.cache` ,
104+ `gatsby-source-filesystem` ,
105+ digest + `.` + type . ext
106+ )
107+ }
108+ }
80109 fs . moveSync ( tmpFilename , filename , { overwrite : true } )
81110 } else {
82111 fs . removeSync ( tmpFilename )
0 commit comments