import got from "got" ; import { ParserService } from "./parseService" ; export async function searchVideo ( searchQuery ) { const YOUTUBE_URL = "https://www.youtube.com" ; const results = [ ] ; let details = [ ] ; let fetched = false ; const options = { type : "video" , limit : 0 } ; const searchRes = await got . get ( encodeURI ( `${ YOUTUBE_URL }/results?search_query=${ searchQuery }` ) ) ; let html = await searchRes . body ; try { const data = html . split ( "ytInitialData = '" ) [ 1 ] . split ( "';</script>" ) [ 0 ] ; html = data . replace ( /\\x([0-9A-F]{2})/gi , ( ... items ) => { return String . fromCharCode ( parseInt ( items [ 1 ] , 16 ) ) ; } ) ; html = html . replaceAll ( '\\\\"' , "" ) ; html = JSON . parse ( html ) ; } catch ( e ) { } if ( html && html . contents && html . contents . sectionListRenderer && html . contents . sectionListRenderer . contents && html . contents . sectionListRenderer . contents . length > 0 && html . contents . sectionListRenderer . contents [ 0 ] . itemSectionRenderer && html . contents . sectionListRenderer . contents [ 0 ] . itemSectionRenderer . contents . length > 0 ) { details = html . contents . sectionListRenderer . contents [ 0 ] . itemSectionRenderer . contents ; fetched = true ; } if ( ! fetched ) { try { details = JSON . parse ( html . split ( '{"itemSectionRenderer":{"contents":' ) [ html . split ( '{"itemSectionRenderer":{"contents":' ) . length - 1 ] . split ( ',"continuations":[{' ) [ 0 ] ) ; fetched = true ; } catch ( e ) { } } if ( ! fetched ) { try { details = JSON . parse ( html . split ( '{"itemSectionRenderer":' ) [ html . split ( '{"itemSectionRenderer":' ) . length - 1 ] . split ( '},{"continuationItemRenderer":{' ) [ 0 ] ) . contents ; fetched = true ; } catch ( e ) { } } if ( ! fetched ) return [ ] ; for ( let i = 0 ; i < details . length ; i ++ ) { if ( typeof options . limit === "number" && options . limit > 0 && results . length >= options . limit ) break ; const data = details [ i ] ; const parserService = new ParserService ( ) ; const parsed = parserService . parseVideo ( data ) ; if ( ! parsed ) continue ; const res = parsed ; results . push ( res ) ; } return results ; }