Added New Method for getting youtube data

This commit is contained in:
killer069
2021-08-08 19:06:00 +05:30
parent f91508d652
commit 1a16c9af20
5 changed files with 524 additions and 42 deletions

View File

@@ -1,5 +1,6 @@
import { get } from "./request";
import fetch from 'node-fetch'
import fs from 'fs'
import got from 'got'
export function valid_url(url : string): boolean{
let valid_url = /^https?:\/\/(youtu\.be\/|(www\.)?youtube\.com\/(embed|watch|v|shorts)(\/|\?))/
@@ -9,37 +10,38 @@ export function valid_url(url : string): boolean{
export async function getBasicInfo(url : string){
if(valid_url(url)){
let body = await get(url)
var final ={
initial_data : yt_initial_data(body)
let body = await url_get(url)
let final = {
player_response : get_ytPlayerResponse(body),
response : get_ytInitialData(body),
js_url : js_url(body)
}
}
else {
throw 'Not a Valid YouTube URL'
process.exit(1)
}
}
function parse_json(str : string, start_index : number){
let matches = 0
let result : string = '';
if(str[start_index] !== '{') {
throw 'Start Index is wrong.'
process.exit(1)
}
matches++
result += str[start_index]
for(let x = start_index + 1; x <= str.length; x++){
if(matches === 0) break
if(str[x] === '(' || str[x] === '{' || str[x] === '[') matches++
if(str[x] === ')' || str[x] === '}' || str[x] === ']') matches--
result += str[x]
}
return JSON.parse(result)
function js_url(data:string): string {
return data.split('"jsUrl":"')[1].split('"')[0]
}
function yt_initial_data(data : string): JSON{
let pattern = /ytInitialData\s=\s/
return parse_json(data, data.search(pattern) + 16)
}
function get_ytPlayerResponse(data : string): JSON {
return JSON.parse(data.split("var ytInitialPlayerResponse = ")[1].split(";</script>")[0])
}
function get_ytInitialData(data:string): JSON {
return JSON.parse(data.split("var ytInitialData = ")[1].split(";</script>")[0])
}
export async function url_get (url : string) : Promise<string>{
return new Promise(async(resolve, reject) => {
let time_start = Date.now()
let response = await fetch(url)
if(response.status === 200) {
resolve(await response.text())
}
else reject(`Got ${response.status} from ${url}`)
})
}