This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/scripts/http.js

124 lines
2.9 KiB
JavaScript

import { URL } from 'url'
import qs from 'querystring'
import fs from 'fs'
export function httpGET (link, headers = {}, lback) {
if (lback && lback >= 4) throw new Error('infinite loop!') // Prevent infinite loop requests
const parsed = new URL(link)
const opts = {
host: parsed.hostname,
port: parsed.port,
path: parsed.pathname,
headers: {
'User-Agent': 'Icy Network Back-end (icynet.eu)',
Accept: '*/*',
'Accept-Language': 'en-GB,enq=0.5'
}
}
if (headers) {
opts.headers = Object.assign(opts.headers, headers)
}
let reqTimeOut
const httpModule = parsed.protocol === 'https:' ? require('https') : require('http')
return new Promise((resolve, reject) => {
const req = httpModule.get(opts, (res) => {
if (res.statusCode === 302 || res.statusCode === 301) {
if (!lback) {
lback = 1
} else {
lback += 1
}
return httpGET(res.headers.location, headers, lback).then(resolve, reject)
}
let data = ''
reqTimeOut = setTimeout(() => {
req.abort()
data = null
reject(new Error('Request took too long!'))
}, 5000)
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
clearTimeout(reqTimeOut)
resolve(data)
})
}).on('error', (e) => {
reject(new Error(e.message))
})
req.setTimeout(10000)
})
}
export function httpPOST (link, headers = {}, data) {
const parsed = new URL(link)
let postData = qs.stringify(data)
const opts = {
host: parsed.host,
port: parsed.port,
path: parsed.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData),
'User-Agent': 'Icy Network Back-end (icynet.eu)'
}
}
if (headers) {
opts.headers = Object.assign(opts.headers, headers)
}
if (opts.headers['Content-Type'] === 'application/json') {
postData = JSON.stringify(data)
}
return new Promise((resolve, reject) => {
const httpModule = parsed.protocol === 'https:' ? require('https') : require('http')
const req = httpModule.request(opts, (res) => {
res.setEncoding('utf8')
let data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
resolve(data)
})
}).on('error', (e) => {
reject(new Error(e))
})
req.write(postData)
req.end()
})
}
export async function downloadURL (url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest)
const protocol = url.indexOf('https:') === 0 ? require('https') : require('http')
protocol.get(url, function (response) {
response.pipe(file)
file.on('finish', function () {
file.close(resolve)
})
}).on('error', function (err) {
fs.unlink(dest)
reject(err)
})
})
}