fimfic2epub/src/fetch.js

80 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2016-06-24 01:26:01 +12:00
2016-06-28 19:39:31 +12:00
import isNode from 'detect-node'
2016-08-23 19:19:01 +12:00
function fetchNode (url, responseType) {
2020-08-10 20:36:02 +12:00
const fetch = require('node-fetch').default
2018-03-13 10:06:35 +13:00
if (url.startsWith('/')) {
2020-09-07 23:40:21 +12:00
url = 'https://www.fimfiction.net' + url
2016-08-23 19:19:01 +12:00
}
return fetch(url, {
method: 'GET',
mode: 'cors',
credentials: 'include',
cache: 'default',
redirect: 'follow',
headers: {
cookie: 'view_mature=true',
2020-09-07 23:40:21 +12:00
referer: 'https://www.fimfiction.net/',
accept: 'Accept: text/*, image/png, image/jpeg' // Fix for not getting webp images from Fimfiction
}
}).then((response) => {
if (responseType) {
return response.buffer()
} else {
return response.text()
}
2016-06-28 19:39:31 +12:00
})
}
2016-08-23 19:19:01 +12:00
export default function fetch (url, responseType) {
2018-03-13 10:06:35 +13:00
if (url.startsWith('//')) {
2016-06-24 01:26:01 +12:00
url = 'http:' + url
}
2016-06-28 19:39:31 +12:00
if (isNode) {
2016-08-23 19:19:01 +12:00
return fetchNode(url, responseType)
2016-06-24 01:26:01 +12:00
}
2020-09-07 23:40:21 +12:00
if (url.startsWith('/')) {
url = window.location.origin + url
}
2016-08-23 19:19:01 +12:00
return new Promise((resolve, reject) => {
if (typeof window.fetch === 'function') {
window.fetch(url, {
method: 'GET',
mode: 'cors',
credentials: 'include',
cache: 'default',
2018-03-13 10:06:35 +13:00
headers: {
accept: 'Accept: text/*, image/png, image/jpeg' // Fix for not getting webp images from Fimfiction
2018-03-13 10:06:35 +13:00
},
2018-03-13 19:12:53 +13:00
referrer: window.location.origin
}).then((response) => {
if (responseType === 'blob') {
response.blob().then(resolve, reject)
} else if (responseType === 'arraybuffer') {
response.arrayBuffer().then(resolve, reject)
} else {
response.text().then(resolve, reject)
}
}).catch((err) => {
2017-10-19 01:59:30 +13:00
reject(new Error('Error fetching ' + url + ' (' + err + ')'))
})
} else {
2019-10-08 22:31:42 +13:00
const x = new XMLHttpRequest()
2018-03-13 10:06:35 +13:00
x.withCredentials = true
x.setRequestHeader('accept', 'text/*, image/png, image/jpeg') // Fix for not getting webp images from Fimfiction
x.open('get', url, true)
if (responseType) {
x.responseType = responseType
}
x.onload = function () {
resolve(x.response)
}
x.onerror = function () {
2017-10-19 01:59:30 +13:00
reject(new Error('Error fetching ' + url))
}
x.send()
2016-08-23 19:19:01 +12:00
}
})
2016-06-24 01:26:01 +12:00
}