youtube

package module
v1.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2020 License: MIT Imports: 24 Imported by: 13

README

Download Youtube Video in Golang

GitHub license GoDoc Build Status Coverage

This package is a Youtube video download package, for more detail refer https://github.com/rg3/youtube-dl for more download options.

Overview

Install:

go get github.com/kkdai/youtube

OR

git clone https://github.com/kkdai/youtube.git
go run youtubedr/main.go

Install in Termux

pkg install youtubedr

Usage

Use the binary directly

It's really simple to use, just get the video id from youtube url - ex: https://www.youtube.com/watch?v=rFejpH_tAHM, the video id is rFejpH_tAHM

$ youtubedr QAGDGja7kbs
$ youtubedr https://www.youtube.com/watch?v=rFejpH_tAHM
Import this package in your golang program
package main

import (
	"flag"
	"fmt"
	"log"
	"os/user"
	"path/filepath"

	. "github.com/kkdai/youtube"
)

func main() {
	flag.Parse()
	log.Println(flag.Args())
	usr, _ := user.Current()
	currentDir := fmt.Sprintf("%v/Movies/youtubedr", usr.HomeDir)
	log.Println("download to dir=", currentDir)
	y := NewYoutube(true)
	arg := flag.Arg(0)
	if err := y.DecodeURL(arg); err != nil {
		fmt.Println("err:", err)
	}
	if err := y.StartDownload(currentDir, "dl.mp4", "medium",0); err != nil {
		fmt.Println("err:", err)
	}
}

Options:

option type description default value
-d string the output directory $HOME/Movies/youtubedr
-o string the output file name ( ext will auto detect on default value ) [video's title].ext
-d string the Socks 5 proxy (e.g. 10.10.10.10:7878)
-q string the output file quality (medium, hd720)
-i string the output file itag (13, 17 etc..) 0
-info bool show information of available streams (quality, itag, MIMEtype)

Example:

  • Get information of dotGo-2015-rob-pike video for downloading

    go get github.com/kkdai/youtube/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr -info https://www.youtube.com/watch?v=rFejpH_tAHM
    
    Title: dotGo 2015 - Rob Pike - Simplicity is Complicated
    Author: dotconferences
    -----available streams-----
    itag:  18 , quality: medium , type: video/mp4; codecs="avc1.42001E, mp4a.40.2"
    itag:  22 , quality:  hd720 , type: video/mp4; codecs="avc1.64001F, mp4a.40.2"
    itag: 137 , quality: hd1080 , type: video/mp4; codecs="avc1.640028"
    itag: 248 , quality: hd1080 , type: video/webm; codecs="vp9"
    ........
    
  • Download dotGo-2015-rob-pike-video

    go get github.com/kkdai/youtube/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video to specific folder and name

    go get github.com/kkdai/youtube/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated to current directory and name the file to simplicity-is-complicated.mp4

    youtubedr -d ./ -o simplicity-is-complicated.mp4 https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video with specific quality

    go get github.com/kkdai/youtube/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated with specific quality

    youtubedr -q medium https://www.youtube.com/watch?v=rFejpH_tAHM
    
    Special case by quality hd1080:

    Installation of ffmpeg is necessary for hd1080

    ffmpeg   //check ffmpeg is installed, if not please download ffmpeg and set to your PATH.
    youtubedr -q hd1080 https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video with specific itag

    go get github.com/kkdai/youtube/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr -i 18 https://www.youtube.com/watch?v=rFejpH_tAHM
    

How it works

  • Parse the video ID you input in URL
    • ex: https://www.youtube.com/watch?v=rFejpH_tAHM, the video id is rFejpH_tAHM
  • Get video information via video id.
    • Use URL: http://youtube.com/get_video_info?video_id=
  • Parse and decode video information.
    • Download URL in "url="
    • title in "title="
  • Download video from URL
    • Need the string combination of "url"

Inspired

Project52

It is one of my project 52.

License

This package is licensed under MIT license. See LICENSE for details.

Documentation

Overview

Package youtube implement youtube download package in go.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyStreamList            = errors.New("empty Stream list")
	ErrItagNotFound               = errors.New("invalid itag value, please specify correct value")
	ErrCipherNotFound             = errors.New("cipher not found")
	ErrInvalidCharactersInVideoId = errors.New("invalid characters in video id")
	ErrVideoIdMinLength           = errors.New("the video id must be at least 10 characters long")
	ErrReadOnClosedResBody        = errors.New("http: read on closed response body")
)

Functions

func SanitizeFilename added in v1.2.2

func SanitizeFilename(fileName string) string

func SetLogOutput

func SetLogOutput(w io.Writer)

SetLogOutput :Set logger writer

Types

type Itag added in v1.2.2

type Itag struct {
	ItagNo  int
	Quality string
	Type    string
}

type PlayerResponseData added in v1.1.0

type PlayerResponseData struct {
	PlayabilityStatus struct {
		Status          string `json:"status"`
		Reason          string `json:"reason"`
		PlayableInEmbed bool   `json:"playableInEmbed"`
		ContextParams   string `json:"contextParams"`
	} `json:"playabilityStatus"`
	StreamingData struct {
		ExpiresInSeconds string `json:"expiresInSeconds"`
		Formats          []struct {
			Stream
			Bitrate          int    `json:"bitrate"`
			Width            int    `json:"width"`
			Height           int    `json:"height"`
			LastModified     string `json:"lastModified"`
			ContentLength    string `json:"contentLength,omitempty"`
			QualityLabel     string `json:"qualityLabel"`
			ProjectionType   string `json:"projectionType"`
			AverageBitrate   int    `json:"averageBitrate,omitempty"`
			AudioQuality     string `json:"audioQuality"`
			ApproxDurationMs string `json:"approxDurationMs"`
			AudioSampleRate  string `json:"audioSampleRate"`
			AudioChannels    int    `json:"audioChannels"`
		} `json:"formats"`
		AdaptiveFormats []struct {
			Stream
			Bitrate   int `json:"bitrate"`
			Width     int `json:"width,omitempty"`
			Height    int `json:"height,omitempty"`
			InitRange struct {
				Start string `json:"start"`
				End   string `json:"end"`
			} `json:"initRange"`
			IndexRange struct {
				Start string `json:"start"`
				End   string `json:"end"`
			} `json:"indexRange"`
			LastModified     string `json:"lastModified"`
			ContentLength    string `json:"contentLength"`
			Fps              int    `json:"fps,omitempty"`
			QualityLabel     string `json:"qualityLabel,omitempty"`
			ProjectionType   string `json:"projectionType"`
			AverageBitrate   int    `json:"averageBitrate"`
			ApproxDurationMs string `json:"approxDurationMs"`
			ColorInfo        struct {
				Primaries               string `json:"primaries"`
				TransferCharacteristics string `json:"transferCharacteristics"`
				MatrixCoefficients      string `json:"matrixCoefficients"`
			} `json:"colorInfo,omitempty"`
			HighReplication bool   `json:"highReplication,omitempty"`
			AudioQuality    string `json:"audioQuality,omitempty"`
			AudioSampleRate string `json:"audioSampleRate,omitempty"`
			AudioChannels   int    `json:"audioChannels,omitempty"`
		} `json:"adaptiveFormats"`
	} `json:"streamingData"`
	PlaybackTracking struct {
		VideostatsPlaybackURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"videostatsPlaybackUrl"`
		VideostatsDelayplayURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"videostatsDelayplayUrl"`
		VideostatsWatchtimeURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"videostatsWatchtimeUrl"`
		PtrackingURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"ptrackingUrl"`
		QoeURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"qoeUrl"`
		SetAwesomeURL struct {
			BaseURL                 string `json:"baseUrl"`
			ElapsedMediaTimeSeconds int    `json:"elapsedMediaTimeSeconds"`
		} `json:"setAwesomeUrl"`
		AtrURL struct {
			BaseURL                 string `json:"baseUrl"`
			ElapsedMediaTimeSeconds int    `json:"elapsedMediaTimeSeconds"`
		} `json:"atrUrl"`
	} `json:"playbackTracking"`
	Captions struct {
		PlayerCaptionsRenderer struct {
			BaseURL    string `json:"baseUrl"`
			Visibility string `json:"visibility"`
		} `json:"playerCaptionsRenderer"`
		PlayerCaptionsTracklistRenderer struct {
			CaptionTracks []struct {
				BaseURL string `json:"baseUrl"`
				Name    struct {
					SimpleText string `json:"simpleText"`
				} `json:"name"`
				VssID          string `json:"vssId"`
				LanguageCode   string `json:"languageCode"`
				Kind           string `json:"kind"`
				IsTranslatable bool   `json:"isTranslatable"`
			} `json:"captionTracks"`
			AudioTracks []struct {
				CaptionTrackIndices []int `json:"captionTrackIndices"`
			} `json:"audioTracks"`
			TranslationLanguages []struct {
				LanguageCode string `json:"languageCode"`
				LanguageName struct {
					SimpleText string `json:"simpleText"`
				} `json:"languageName"`
			} `json:"translationLanguages"`
			DefaultAudioTrackIndex int `json:"defaultAudioTrackIndex"`
		} `json:"playerCaptionsTracklistRenderer"`
	} `json:"captions"`
	VideoDetails struct {
		VideoID          string `json:"videoId"`
		Title            string `json:"title"`
		LengthSeconds    string `json:"lengthSeconds"`
		ChannelID        string `json:"channelId"`
		IsOwnerViewing   bool   `json:"isOwnerViewing"`
		ShortDescription string `json:"shortDescription"`
		IsCrawlable      bool   `json:"isCrawlable"`
		Thumbnail        struct {
			Thumbnails []struct {
				URL    string `json:"url"`
				Width  int    `json:"width"`
				Height int    `json:"height"`
			} `json:"thumbnails"`
		} `json:"thumbnail"`
		AverageRating     float64 `json:"averageRating"`
		AllowRatings      bool    `json:"allowRatings"`
		ViewCount         string  `json:"viewCount"`
		Author            string  `json:"author"`
		IsPrivate         bool    `json:"isPrivate"`
		IsUnpluggedCorpus bool    `json:"isUnpluggedCorpus"`
		IsLiveContent     bool    `json:"isLiveContent"`
	} `json:"videoDetails"`
	PlayerConfig struct {
		AudioConfig struct {
			LoudnessDb              float64 `json:"loudnessDb"`
			PerceptualLoudnessDb    float64 `json:"perceptualLoudnessDb"`
			EnablePerFormatLoudness bool    `json:"enablePerFormatLoudness"`
		} `json:"audioConfig"`
		StreamSelectionConfig struct {
			MaxBitrate string `json:"maxBitrate"`
		} `json:"streamSelectionConfig"`
		MediaCommonConfig struct {
			DynamicReadaheadConfig struct {
				MaxReadAheadMediaTimeMs int `json:"maxReadAheadMediaTimeMs"`
				MinReadAheadMediaTimeMs int `json:"minReadAheadMediaTimeMs"`
				ReadAheadGrowthRateMs   int `json:"readAheadGrowthRateMs"`
			} `json:"dynamicReadaheadConfig"`
		} `json:"mediaCommonConfig"`
	} `json:"playerConfig"`
	Storyboards struct {
		PlayerStoryboardSpecRenderer struct {
			Spec string `json:"spec"`
		} `json:"playerStoryboardSpecRenderer"`
	} `json:"storyboards"`
	Microformat struct {
		PlayerMicroformatRenderer struct {
			Thumbnail struct {
				Thumbnails []struct {
					URL    string `json:"url"`
					Width  int    `json:"width"`
					Height int    `json:"height"`
				} `json:"thumbnails"`
			} `json:"thumbnail"`
			Embed struct {
				IframeURL      string `json:"iframeUrl"`
				FlashURL       string `json:"flashUrl"`
				Width          int    `json:"width"`
				Height         int    `json:"height"`
				FlashSecureURL string `json:"flashSecureUrl"`
			} `json:"embed"`
			Title struct {
				SimpleText string `json:"simpleText"`
			} `json:"title"`
			Description struct {
				SimpleText string `json:"simpleText"`
			} `json:"description"`
			LengthSeconds      string   `json:"lengthSeconds"`
			OwnerProfileURL    string   `json:"ownerProfileUrl"`
			ExternalChannelID  string   `json:"externalChannelId"`
			AvailableCountries []string `json:"availableCountries"`
			IsUnlisted         bool     `json:"isUnlisted"`
			HasYpcMetadata     bool     `json:"hasYpcMetadata"`
			ViewCount          string   `json:"viewCount"`
			Category           string   `json:"category"`
			PublishDate        string   `json:"publishDate"`
			OwnerChannelName   string   `json:"ownerChannelName"`
			UploadDate         string   `json:"uploadDate"`
		} `json:"playerMicroformatRenderer"`
	} `json:"microformat"`
	TrackingParams string `json:"trackingParams"`
	Attestation    struct {
		PlayerAttestationRenderer struct {
			Challenge    string `json:"challenge"`
			BotguardData struct {
				Program        string `json:"program"`
				InterpreterURL string `json:"interpreterUrl"`
			} `json:"botguardData"`
		} `json:"playerAttestationRenderer"`
	} `json:"attestation"`
	Messages []struct {
		MealbarPromoRenderer struct {
			MessageTexts []struct {
				Runs []struct {
					Text string `json:"text"`
				} `json:"runs"`
			} `json:"messageTexts"`
			ActionButton struct {
				ButtonRenderer struct {
					Style string `json:"style"`
					Size  string `json:"size"`
					Text  struct {
						Runs []struct {
							Text string `json:"text"`
						} `json:"runs"`
					} `json:"text"`
					ServiceEndpoint struct {
						ClickTrackingParams string `json:"clickTrackingParams"`
						CommandMetadata     struct {
							WebCommandMetadata struct {
								URL      string `json:"url"`
								SendPost bool   `json:"sendPost"`
								APIURL   string `json:"apiUrl"`
							} `json:"webCommandMetadata"`
						} `json:"commandMetadata"`
						FeedbackEndpoint struct {
							FeedbackToken string `json:"feedbackToken"`
							UIActions     struct {
								HideEnclosingContainer bool `json:"hideEnclosingContainer"`
							} `json:"uiActions"`
						} `json:"feedbackEndpoint"`
					} `json:"serviceEndpoint"`
					NavigationEndpoint struct {
						ClickTrackingParams string `json:"clickTrackingParams"`
						CommandMetadata     struct {
							WebCommandMetadata struct {
								URL         string `json:"url"`
								WebPageType string `json:"webPageType"`
								RootVe      int    `json:"rootVe"`
							} `json:"webCommandMetadata"`
						} `json:"commandMetadata"`
						BrowseEndpoint struct {
							BrowseID string `json:"browseId"`
							Params   string `json:"params"`
						} `json:"browseEndpoint"`
					} `json:"navigationEndpoint"`
					TrackingParams string `json:"trackingParams"`
				} `json:"buttonRenderer"`
			} `json:"actionButton"`
			DismissButton struct {
				ButtonRenderer struct {
					Style string `json:"style"`
					Size  string `json:"size"`
					Text  struct {
						Runs []struct {
							Text string `json:"text"`
						} `json:"runs"`
					} `json:"text"`
					ServiceEndpoint struct {
						ClickTrackingParams string `json:"clickTrackingParams"`
						CommandMetadata     struct {
							WebCommandMetadata struct {
								URL      string `json:"url"`
								SendPost bool   `json:"sendPost"`
								APIURL   string `json:"apiUrl"`
							} `json:"webCommandMetadata"`
						} `json:"commandMetadata"`
						FeedbackEndpoint struct {
							FeedbackToken string `json:"feedbackToken"`
							UIActions     struct {
								HideEnclosingContainer bool `json:"hideEnclosingContainer"`
							} `json:"uiActions"`
						} `json:"feedbackEndpoint"`
					} `json:"serviceEndpoint"`
					TrackingParams string `json:"trackingParams"`
				} `json:"buttonRenderer"`
			} `json:"dismissButton"`
			TriggerCondition    string `json:"triggerCondition"`
			Style               string `json:"style"`
			TrackingParams      string `json:"trackingParams"`
			ImpressionEndpoints []struct {
				ClickTrackingParams string `json:"clickTrackingParams"`
				CommandMetadata     struct {
					WebCommandMetadata struct {
						URL      string `json:"url"`
						SendPost bool   `json:"sendPost"`
						APIURL   string `json:"apiUrl"`
					} `json:"webCommandMetadata"`
				} `json:"commandMetadata"`
				FeedbackEndpoint struct {
					FeedbackToken string `json:"feedbackToken"`
					UIActions     struct {
						HideEnclosingContainer bool `json:"hideEnclosingContainer"`
					} `json:"uiActions"`
				} `json:"feedbackEndpoint"`
			} `json:"impressionEndpoints"`
			IsVisible    bool `json:"isVisible"`
			MessageTitle struct {
				Runs []struct {
					Text string `json:"text"`
				} `json:"runs"`
			} `json:"messageTitle"`
		} `json:"mealbarPromoRenderer"`
	} `json:"messages"`
}

type Stream added in v1.2.3

type Stream struct {
	ItagNo   int    `json:"itag"`
	URL      string `json:"url"`
	MimeType string `json:"mimeType"`
	Quality  string `json:"quality"`
	Cipher   string `json:"signatureCipher"`
}

type StreamInfo added in v1.2.3

type StreamInfo struct {
	Title   string
	Author  string
	Streams []Stream
}

type Youtube

type Youtube struct {
	DebugMode  bool
	StreamList []Stream
	VideoID    string

	DownloadPercent chan int64
	Socks5Proxy     string

	Title  string
	Author string

	// Disable SSL certificate verification
	InsecureSkipVerify bool
	// contains filtered or unexported fields
}

Youtube implements the downloader to download youtube videos.

func NewYoutube

func NewYoutube(debug bool, insecureSkipVerify bool) *Youtube

NewYoutube :Initialize youtube package object.

Example

ExampleDownload : Example code for how to use this package for download video.

package main

import (
	"flag"
	"fmt"
	"log"
	"os/user"

	"github.com/kkdai/youtube"
)

func main() {
	flag.Parse()
	log.Println(flag.Args())
	usr, _ := user.Current()
	currentDir := fmt.Sprintf("%v/Movies/youtubedr", usr.HomeDir)
	log.Println("download to dir=", currentDir)
	y := youtube.NewYoutube(true, false)
	arg := flag.Arg(0)
	if err := y.DecodeURL(arg); err != nil {
		fmt.Println("err:", err)
	}
	if err := y.StartDownload(currentDir, "dl.mp4", "", 0); err != nil {
		fmt.Println("err:", err)
	}
}
Output:

func NewYoutubeWithSocks5Proxy added in v1.1.0

func NewYoutubeWithSocks5Proxy(debug bool, socks5Proxy string, insecureSkipVerify bool) *Youtube

func (Youtube) Close added in v1.2.3

func (y Youtube) Close(r io.ReadCloser, op string)

func (*Youtube) DecodeURL

func (y *Youtube) DecodeURL(url string) error

DecodeURL : Decode youtube URL to retrieval video information.

func (*Youtube) GetStreamInfo added in v1.2.3

func (y *Youtube) GetStreamInfo() *StreamInfo

func (*Youtube) StartDownload

func (y *Youtube) StartDownload(outputDir, outputFile, quality string, itagNo int) error

StartDownload : Starting download video by arguments.

func (*Youtube) StartDownloadWithHighQuality added in v1.2.3

func (y *Youtube) StartDownloadWithHighQuality(outputDir string, outputFile string, quality string) error

StartDownloadWithHighQuality : Starting downloading video with high quality (>720p).

func (*Youtube) Write

func (y *Youtube) Write(p []byte) (n int, err error)

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL