Skip to content
gatecrasher777 edited this page Feb 15, 2022 · 19 revisions

Video

Methods

constructor

const video = ytcog.Video(session, videoOptions);

session is an instance of a ytcog.Session
videoOptions is a user defined object explained below

fetch

fetch() collects video metadata, storyboard and streams. It deciphers and transforms streams to ensure fast, reliable downloads.

await video.fetch([videoOptions]);

download

download() runs a forked process to download a video based on the videoOptions supplied.

await video.download([videoOptions]);

cancel

cancel() cancels an active download.

video.cancel();

hasComments

video.hasComments() returns true if the video has comments, false if there are no comments or comments are disabled. After this query, the number of comments available are given by the property video.commentCount.

if (await video.hasComments()) {
   console.log(`This video has ${video.commentCount} comments.`);
}

fetchComments

fetchComments(commentOptions) collects viewer comments (if available) on the video.

await video.fetchComments({
  order: 'top',
  quantity: 20,
  replies: false
})

commentOptions is a user defined object explained below

commentsText

video.commentsText(commentOptions) creates a comments .txt file based on the commentOptions (written to the same destination path as video and subtitle files)

await video.commentsText(commentOptions);

commentOptions is a user defined object explained below

imageOnline

imageOnline() is an inexpensive method to check online status of a video. Check video status (reason) after execution. Either OK () or NOK (Head request error. Status Code: 404).

await video.imageOnline();

Properties

Video objects can have the following properties.

video.status        (string) The result of the last fetch(), continued() or download() operations: Either OK,NOK or ERROR
video.reason        (string) The reason for status NOK or ERROR.
video.updated       (number) Timestamp of last fetch.
video.data          (string) or [(string)] The raw YouTube data fetched.
video.transferred   (number) Cumulative number of bytes of incoming data (compressed with gzip library). 
video.debugOn       (boolean) default is false. Set to true to get error information in the console. 
video.channelId     (string) The video's channel id
video.duration      (number) The duration of the video in seconds.
video.expiry        (number) The lifespan in seconds of the video streams collected
video.views         (number) The number of views received by the video
video.rating        (number) The rating of the video (1 to 5 or -1 if no ratings given)
video.published     (number) Timestamp of published time (if known or 0 if unknown)
video.downloaded    (number) Timestamp of when you completed downloading the video (or 0).
video.canEmbed      (boolean) The video can be watched embedded on 3rd party html page.
video.isLive        (boolean) The video is a live event.
video.title         (string) The title of the video.
video.category      (string) The YouTube category of the video (ie sport, games, people & blogs etc.)
video.description   (string) The description of the video.
video.author        (string) The display name of the video author.
video.channelThumb  (string) Thumbnail url of the channel logo
video.country       (string) Country of origin of the channel
video.fn            (string) The filepath of the downloaded video (or an empty string)
video.keywords      ([string]) An array of keywords to identify the video contents
video.storyBoards   ([object]) A user friendly extraction of the storyboard images 
video.videoStreams  ([object]) A user friendly extraction of the video streams with urls deciphered/encoded ready for download.
video.audioStreams  ([object]) A user friendly extraction of the audio streams with urls deciphered/encoded ready for download.
video.formats       ([object]) An array of the original json streams
video.cancelled     (boolean) Whether the current download has been cancelled.
video.streamInfo    (object) A convenient object that gives index numbers and concise stream information for easy stream selection.
video.hasMedia      (boolean) Whether media streams are available.
video.timeToExpiry  (number) The number of seconds left before the media streams expire.
video.captions      ([object]) An array of caption/subtitle links/languages
video.defaultCaption (number) Index of the default caption track
video.comments      ([object]) An array of comment objects
video.results       ([object]) An array of comments from the last call to fetchComments.
video.commentCount  (number) The number of comments available.
video.commentData   ([object]) The raw YouTube comment data fetched.

Options

videoOptions is an object with the following properties:

Required:

id:  (11 character string) the video id.

Optional:

published:     (number) Optional published timestamp (used internally).   

path:          (string) path to your download folder - defaults to the current directory.

filename:      (string) supply a filename without path or extension - you can use ${templates}  
               in your filename string, such as:

                * ${audioCodec}         - aac, opus, mp3 or flac
                * ${author}             - channel display name
                * ${channelId}          - channel id of video
                * ${date}               - YYYYMMDD - published date for video
                * ${datetime}           - YYYYMMDD HHMMSS - published date & time for video
                * ${id}                 - video id
                * ${timestamp}          - unix timestamp - published timestamp for video
                * ${title}              - video title
                * ${videoCodec}         - h264 or vp9
                * ${videoQuality}       - i.e. 1080p, 360p, etc
                * ${...}                - you can use any other video/channel/search info properties
               The default filename is:  
               "${author}_${datetime}_${title}_${id}_${videoQuality}_${videoCodec}_${audioCodec}"

container:     (string) your desired media container: 
                * any    no preference between mp4 (h264 with aac) or webm (vp9 with opus) (default)
                * mp4    prefers mp4 codecs to webm codecs but defers to the videoQuality preference
                * webm   prefers webm codecs to mp4 codecs but defers to the videoQuality preference
                * mkv    uses the most preferred streams regardless of codecs and allows mixed video
                         and audio formats (vp9 with aac) or (mp4 with opus)
                * mp3    enforces audio only and converts to an .mp3 file
                * flac   enforces audio only and converts to a lossless .flac file

videoQuality:  (string) your desired video quality: 
                * highest            highest possible quality (up to 4k)
                * 1080p              nearest to 1080p Full HD (default)    
                * 720p               nearest to 720p HD
                * 480p               nearest to 480p
                * medium             medium quality
                * 360p               nearest to 360p
                * 240p               nearest to 240p
                * 144p               nearest to 144p
                * lowest             lowest possible quality
                * none               no video, download audio only

audioQuality:  (string) your desired audio quality: 
                * highest            highest possible quality
                * medium             medium quality (default)
                * lowest             lowest possible quality
                * none               no audio, download video only  

mediaBitrate:  (string) when comparing bitrates of streams of equal resolution/quality
                * highest            choose the stream with the highest bitrate (default) 
                * lowest             choose the stream with the lowest bitrate

metadata:      (string) to embed properties in the downloaded video. One or more of the following, in 
               a comma separated string: 
                * title               the video title
                * author              the video author
                * description         the video description
                * keywords            the video keywords 
                * published           the date published  
                * key=text            any custom key and text. 
               In text you can use ${templates} to embed any video property, similar to filename.
               The default is an empty string. No metadata is embedded by default.

subtitles:     (string) create captions/subtitles file(s) for downloads if available.
               A comma separated list of language codes. For example: 'en,es,ja' for English, Spanish
               Japanese. See the list below. Default is 'none' - do not make subtitle files.

subtitleFormat: (string) choose the format(s) for your subtitle files. 
                 * srt
                 * ttml
                 * vtt
                Default is "srt". You can add additional formats ie "srt,ttml,vtt".

videoFormat:   (number) choose a specific video stream (default: -1 uses above options to rank and 
               select video streams).  

audioFormat:   (number) choose a specific audio stream (default: -1 uses above options to rank and  
               select audio streams).  

progress:      (function) provide a download progress callback. 

Example:

Fetch/download with custom filename string. Want best possible quality. Don't care which codecs are used. Its for a media player. Don't need it to play in an HTML5 video tag. Embed with metadata (since the filename is obscure). Include English subtitles if available.

{
    id: 'UoHEvzQc0O4',
    filename: '${channelId} - ${datetime} - ${id} - ${videoQuality}',
    container: 'mkv',
    videoQuality: 'highest',
    audioQuality: 'highest',
    mediaBitrate: 'highest',
    metadata: 'author,title,genre=sport,year=2021',
    subtitles: 'en'
}

Progress Callback:

The progress callback, if provided, can accept three arguments:

prg: (number) a percentage completion indicator 0-100
siz: (number) the number of bytes downloaded since the last progress update
tot: (number) the total size of the downloading media

For example:

let bytesDownloaded = 0;
await video.download({
    progress: (prg, siz, tot)=>{
        bytesDownloaded += size;
        process.stdout.write( `Progress ${Math.floor(prog)}%  ${bytesDownloaded}/${total} bytes    \r` );
    } 
});
console.log( `\nTotal bytes downloaded: ${bytesDownloaded}` );

Comment Options

commentOptions is an object with the following properties:

Optional:

filename:      (string) supply a filename without path or extension - you can use ${templates}  
               in your filename string as in video options. The default comments filename is:  
               "${author}_${datetime}_${title}_${id}_comments.txt"

order:         (string) top/new - Order of comments. top - most popular, new - most recent. Default: top

quantity:      (number) the minimum number of comments to collect (if available) - 
               set to 0 download all comments. Default: 20.

replies:       (boolean) if true include replies to comments.  Default: false, direct comments only.

Language codes

af  Afrikaans
sq  Albanian
am  Amharic
ar  Arabic
hy  Armenian
az  Azerbaijani
bn  Bangla
eu  Basque
be  Belarusian
bs  Bosnian
bg  Bulgarian
my  Burmese
ca  Catalan
ceb  Cebuano
zh-Hans  Chinese (Simplified)
zh-Hant  Chinese (Traditional)
co  Corsican
hr  Croatian
cs  Czech
da  Danish
nl  Dutch
en  English
eo  Esperanto
et  Estonian
fil Filipino
fi  Finnish
fr  French
gl  Galician
ka  Georgian
de  German
el  Greek
gu  Gujarati
ht  Haitian Creole
ha  Hausa
haw Hawaiian
iw  Hebrew
hi  Hindi
hmn Hmong
hu  Hungarian
is  Icelandic
ig  Igbo
id  Indonesian
ga  Irish
it  Italian
ja  Japanese
jv  Javanese
kn  Kannada
kk  Kazakh
km  Khmer
rw  Kinyarwanda
ko  Korean
ku  Kurdish
ky  Kyrgyz
lo  Lao
la  Latin
lv  Latvian
lt  Lithuanian
lb  Luxembourgish
mk  Macedonian
mg  Malagasy
ms  Malay
ml  Malayalam
mt  Maltese
mi  Maori
mr  Marathi
mn  Mongolian
ne  Nepali
no  Norwegian
ny  Nyanja
or  Odia
ps  Pashto
fa  Persian
pl  Polish
pt  Portuguese
pa  Punjabi
ro  Romanian
ru  Russian
sm  Samoan
gd  Scottish Gaelic
sr  Serbian
sn  Shona
sd  Sindhi
si  Sinhala
sk  Slovak
sl  Slovenian
so  Somali
st  Southern Sotho
es  Spanish
su  Sundanese
sw  Swahili
sv  Swedish
tg  Tajik
ta  Tamil
tt  Tatar
te  Telugu
th  Thai
tr  Turkish
tk  Turkmen
uk  Ukrainian
ur  Urdu
ug  Uyghur
uz  Uzbek
vi  Vietnamese
cy  Welsh
fy  Western Frisian
xh  Xhosa
yi  Yiddish
yo  Yoruba
zu  Zulu