Files
play-dl-test/play-dl/YouTube/utils/request.ts

62 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-09-17 14:36:32 +05:30
import https, { RequestOptions } from 'https';
import { IncomingMessage } from 'http';
import { URL } from 'url';
2021-09-13 00:31:52 +05:30
2021-09-17 14:36:32 +05:30
interface RequestOpts extends RequestOptions {
body?: string;
method?: 'GET' | 'POST';
2021-09-13 00:31:52 +05:30
}
2021-09-17 14:36:32 +05:30
function https_getter(req_url: string, options: RequestOpts = {}): Promise<IncomingMessage> {
2021-09-13 00:31:52 +05:30
return new Promise((resolve, reject) => {
2021-09-17 14:36:32 +05:30
const s = new URL(req_url);
options.method ??= 'GET';
const req_options: RequestOptions = {
host: s.hostname,
path: s.pathname + s.search,
headers: options.headers ?? {},
method: options.method
};
2021-09-13 00:31:52 +05:30
2021-09-17 14:36:32 +05:30
const req = https.request(req_options, resolve);
2021-09-14 22:06:07 +05:30
req.on('error', (err) => {
2021-09-17 14:36:32 +05:30
reject(err);
});
if (options.method === 'POST') req.write(options.body);
req.end();
});
2021-09-04 20:38:39 +09:00
}
2021-09-13 00:31:52 +05:30
2021-09-17 14:36:32 +05:30
export async function request(url: string, options?: RequestOpts): Promise<string> {
2021-09-13 00:31:52 +05:30
return new Promise(async (resolve, reject) => {
2021-09-17 14:36:32 +05:30
let data = '';
let res = await https_getter(url, options).catch((err: Error) => err);
if (res instanceof Error) {
reject(res);
return;
2021-09-13 00:31:52 +05:30
}
2021-09-17 14:36:32 +05:30
if (Number(res.statusCode) >= 300 && Number(res.statusCode) < 400) {
res = await https_getter(res.headers.location as string, options);
} else if (Number(res.statusCode) > 400) {
reject(new Error(`Got ${res.statusCode} from the request`));
2021-09-13 00:31:52 +05:30
}
2021-09-17 14:36:32 +05:30
res.setEncoding('utf-8');
res.on('data', (c) => (data += c));
res.on('end', () => resolve(data));
});
2021-09-13 00:31:52 +05:30
}
2021-09-17 14:36:32 +05:30
export async function request_stream(url: string, options?: RequestOpts): Promise<IncomingMessage> {
2021-09-13 00:31:52 +05:30
return new Promise(async (resolve, reject) => {
2021-09-17 14:36:32 +05:30
let res = await https_getter(url, options).catch((err: Error) => err);
if (res instanceof Error) {
reject(res);
return;
}
if (Number(res.statusCode) >= 300 && Number(res.statusCode) < 400) {
res = await https_getter(res.headers.location as string, options);
2021-09-13 00:31:52 +05:30
}
2021-09-17 14:36:32 +05:30
resolve(res);
});
2021-09-13 14:30:59 +09:00
}