gotube

package module
v0.0.0-...-36b9210 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2025 License: MIT Imports: 7 Imported by: 0

README

gotube

Go Reference Go Version Sourcegraph Discussions TODOs

gotube is a Go library for performing YouTube searches and extracting video data seamlessly. This library provides a simple interface to search for videos on YouTube, retrieve associated data, and facilitate further processing.

Features

  • YouTube Search: Easily perform searches for videos on YouTube based on specified search terms.
  • Video Data Extraction: Extract relevant information about each video, such as video ID, title, views, duration, and more.
  • Optimized Performance: Utilizes the fasthttp library for efficient HTTP requests and responses.
  • Efficient JSON Parsing: Uses the go-json library for fast and efficient JSON parsing.

Installation

To use the gotube library in your Go project, you can fetch it using go get:

go get github.com/rezatg/gotube

Structs and Methods

SearchOptions Struct The SearchOptions struct defines the parameters for a YouTube search query:
  • SearchTerms: The search query string.
  • Limit: The maximum number of results to retrieve (not actively used in the current implementation).
Example Usage
package main

import (
   "fmt"
   "github.com/rezatg/gotube"
)

func main() {
   // Create a new GoTube instance.
   youtube := gotube.NewGoTube()

   // Perform a YouTube search with the search term "Ali Sorena, Negar" and limit the max-results to 1
   results, _ := gotube.Search(&gotube.SearchOptions{
      SearchTerms: "Ali Sorena, Negar",
      Limit: 1,
   })

   // Print details for the first result.
   videoInfo := result[0]
   fmt.Printf("ID: %s\nTitle: %s\nThumbnail URL: %s\nThumbnails: %v\nChannel: %s\nDuration: %s\nViews: %s\nURL Suffix: %s\nURL: %s\nPublish Time: %s\n",
      videoInfo.ID,
      videoInfo.GetTitle(),
      videoInfo.GetUrlThumbnail(),
      videoInfo.GetThumbnails(),
      videoInfo.GetChannel(),
      videoInfo.GetDuration(),
      videoInfo.GetViews(),
      videoInfo.GetUrlSuffix(),
      videoInfo.GetUrl(),
      videoInfo.GetPublishTime(),
   )
}

Get Video Information

You can retrieve detailed information about a specific video using the GetInfoVideo method. Here is an example based on examples/main.go:

package main

import (
   "fmt"
   "log"

   "github.com/rezatg/gotube"
)

func main() {
   // Create a new GoTube instance.
   youtube := gotube.NewGoTube()

   // Specify the YouTube video URL.  
   videoURL := "https://youtu.be/1r8sEJTtwzE?si=jOvHjVawN-2cgQKi"


   // Retrieve video information.
   videoInfo, err := youtube.GetInfoVideo(videoURL)
   if err != nil {
      log.Fatalf("Error getting video info: %v", err)
   }

   // Access and print the desired information.  See below for a full list of available fields.
   fmt.Println("Video Title:", videoInfo.GetTitle())
   fmt.Println("Channel:", videoInfo.GetChannel())
   fmt.Println("Views:", videoInfo.GetViews())
   fmt.Println("Description:", videoInfo.GetDescription())
   // ... access other fields as needed
}

Available Fields (GetInfoVideo):

The GetInfoVideo method returns a VideoData struct, which provides access to a variety of video details through its methods :

  • ID(): Returns the video ID.
  • GetTitle(): Returns the video title.
  • GetDescription(): Returns the video description.
  • GetChannel(): Returns the channel name.
  • GetUrlThumbnail(): Returns the URL of the video thumbnail.
  • GetDuration(): Returns the video duration.
  • GetLikeCount(): Returns the like count.
  • GetPublishTime(): Returns the publish time.
  • GetRelativeDate(): Returns the relative publish date (e.g., "2 weeks ago").
  • GetViews(): Returns the view count.
  • GetShortView(): Returns the abbreviated view count (e.g., "1.2M views").
  • GetSubscriberCount(): Returns the subscriber count of the channel.
  • GetUrlSuffix(): Returns the URL suffix of the video.
  • GetUrl(): Returns the full URL of the video.

Error Handling

The GetInfoVideo method may return errors in the following cases:

  • Invalid Video URL: If the provided URL is incorrect or malformed.
  • Network Issues: If there are connectivity issues or server errors.

It is recommended to handle errors appropriately, as shown in the examples.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CompactVideoRenderer

type CompactVideoRenderer struct {
	ID string `json:"videoId"`

	Thumbnail         Thumbnail         `json:"thumbnail"`
	Title             Title             `json:"title"`
	LongBylineText    LongBylineText    `json:"longBylineText"`
	PublishedTimeText PublishedTimeText `json:"publishedTimeText"`
	LengthText        LengthText        `json:"lengthText"`
	ViewCountText     ViewCountText     `json:"viewCountText"`

	NavigationEndpoint NavigationEndpoint `json:"navigationEndpoint"`
}

CompactVideoRenderer contains summary information for a video.

func ParseHtmlSearch

func ParseHtmlSearch(response []byte, limit int) ([]CompactVideoRenderer, error)

ParseHtmlSearch extracts video data from the parsed JSON response. It takes the HTML response and a limit for the number of videos to extract.

func (*CompactVideoRenderer) GetChannel

func (cr *CompactVideoRenderer) GetChannel() string

GetChannel returns the name of the channel.

func (*CompactVideoRenderer) GetDuration

func (cr *CompactVideoRenderer) GetDuration() string

GetDuration extracts the video duration.

func (*CompactVideoRenderer) GetPublishTime

func (cr *CompactVideoRenderer) GetPublishTime() string

GetPublishTime extracts the video publish time.

func (*CompactVideoRenderer) GetThumbnails

func (cr *CompactVideoRenderer) GetThumbnails() []Thumbnails

GetThumbnails retrieves the list of all thumbnail information for the video.

func (*CompactVideoRenderer) GetTitle

func (cr *CompactVideoRenderer) GetTitle() string

GetTitle returns the title of the video.

func (*CompactVideoRenderer) GetUrl

func (cr *CompactVideoRenderer) GetUrl() string

GetUrl constructs the full URL for the video.

func (*CompactVideoRenderer) GetUrlSuffix

func (cr *CompactVideoRenderer) GetUrlSuffix() string

GetUrlSuffix extracts the video URL suffix.

func (*CompactVideoRenderer) GetUrlThumbnail

func (cr *CompactVideoRenderer) GetUrlThumbnail() string

GetThumbnail retrieves the first thumbnail URL from the list of thumbnails associated with the video.

func (*CompactVideoRenderer) GetViews

func (cr *CompactVideoRenderer) GetViews() string

GetViews extracts the video view count.

type Description

type Description struct {
	Content string `json:"content"`
}

Description represents a description structure.

type GoTube

type GoTube struct {
	// contains filtered or unexported fields
}

GoTube is a wrapper structure to manage default context and timeout for requests.

func NewGoTube

func NewGoTube() *GoTube

NewGoTube creates a new instance of GoTube with a default timeout.

func (GoTube) GetInfoVideo

func (gt GoTube) GetInfoVideo(url string) (*VideoData, error)

GetInfoVideo retrieves video information from a given YouTube video URL. It sends an HTTP GET request to the URL, parses the HTML response, and returns a VideoData struct containing the video's information. Note: This function relies on the HTML structure of the YouTube video page. Changes to YouTube's HTML may break this function. Error handling is implemented for network requests, but not for parsing errors within ParseHtmlInfoVideo. Consider adding more robust error handling in the future.

func (GoTube) Search

func (gt GoTube) Search(opt *SearchOptions) ([]CompactVideoRenderer, error)

Search performs a YouTube search using the provided options. It constructs the search URL, sends an HTTP GET request, and prints the raw response body. Note: This function currently doesn't handle pagination or result parsing, it only retrieves the raw HTML.

type LengthText

type LengthText struct {
	Accessibility struct {
		AccessibilityData struct {
			Label string `json:"label"`
		} `json:"accessibilityData"`
	} `json:"accessibility"`
	SimpleText string `json:"simpleText"`
}

LengthText represents the video length, including accessibility information.

type LongBylineText

type LongBylineText struct {
	Runs []struct {
		Text string `json:"text"`
	} `json:"runs"`
}

LongBylineText represents the long channel name or description, including navigation details.

type NavigationEndpoint struct {
	CommandMetadata struct {
		WebCommandMetadata struct {
			Url string `json:"url"`
		} `json:"webCommandMetadata"`
	} `json:"commandMetadata"`
}

NavigationEndpoint represents the navigation endpoint for the video.

type Owner

type Owner struct {
	VideoOwnerRenderer struct {
		Title struct {
			Runs [1]struct {
				Text string `json:"text"`
			} `json:"runs"`
		} `json:"title"`
		SubscriberCountText SimpleText `json:"subscriberCountText"`
	} `json:"videoOwnerRenderer"`
}

Owner represents the owner of a video.

type PublishedTimeText

type PublishedTimeText struct {
	SimpleText string `json:"simpleText"`
}

PublishedTimeText represents the simple text for the video's publish date.

type SearchOptions

type SearchOptions struct {
	SearchTerms string // Search query string
	Limit       int    // Maximum number of results to retrieve
}

OptionsSearch defines the options for a YouTube search query.

type SimpleText

type SimpleText struct {
	SimpleText string `json:"simpleText"`
}

SimpleText represents a simple text structure.

type Thumbnail

type Thumbnail struct {
	Thumbnails []Thumbnails `json:"thumbnails"`
}

Thumbnail represents thumbnail information for a video. Contains an array of thumbnail URLs with dimensions.

type Thumbnails

type Thumbnails struct {
	URL    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

Thumbnail represents thumbnail information for a video. Contains an array of thumbnail URLs with dimensions.

type Title

type Title struct {
	Runs []struct {
		Text string `json:"text"`
	} `json:"runs"`
	Accessibility struct {
		AccessibilityData struct {
			Label string `json:"label"`
		} `json:"accessibilityData"`
	} `json:"accessibility"`
}

Title represents the title of a video, including accessibility information.

type VideoActions

type VideoActions struct {
	MenuRenderer struct {
		TopLevelButtons []struct {
			SegmentedLikeDislikeButtonViewModel struct {
				LikeButtonViewModel struct {
					LikeButtonViewModel struct {
						ToggleButtonViewModel struct {
							ToggleButtonViewModel struct {
								DefaultButtonViewModel struct {
									ButtonViewModel struct {
										Title string `json:"title"`
									} `json:"buttonViewModel"`
								} `json:"defaultButtonViewModel"`
							} `json:"toggleButtonViewModel"`
						} `json:"toggleButtonViewModel"`
					} `json:"likeButtonViewModel"`
				} `json:"likeButtonViewModel"`
			} `json:"segmentedLikeDislikeButtonViewModel"`
		} `json:"topLevelButtons"`
	} `json:"menuRenderer"`
}

VideoActions represents the actions available for a video.

type VideoData

type VideoData struct {
	CompactVideoRenderer       *CompactVideoRenderer       `json:"compactVideoRenderer,omitempty"`
	VideoPrimaryInfoRenderer   *VideoPrimaryInfoRenderer   `json:"videoPrimaryInfoRenderer,omitempty"`
	VideoSecondaryInfoRenderer *VideoSecondaryInfoRenderer `json:"videoSecondaryInfoRenderer,omitempty"`
}

VideoData holds detailed video information.

func ParseHtmlInfoVidoe

func ParseHtmlInfoVidoe(response []byte) (*VideoData, error)

ParseHtmlInfoVideo extracts detailed video information from the parsed JSON response. It takes the HTML response and returns a VideoData struct containing the video's information.

func (*VideoData) GetChannel

func (vd *VideoData) GetChannel() string

GetChannel returns the name of the channel.

func (*VideoData) GetDescription

func (vd *VideoData) GetDescription() string

GetDescription extracts the video description.

func (*VideoData) GetDuration

func (vd *VideoData) GetDuration() string

GetDuration extracts the video duration.

func (*VideoData) GetLikeCount

func (vd *VideoData) GetLikeCount() string

GetLikeCount extracts the video like count.

func (*VideoData) GetPublishTime

func (vd *VideoData) GetPublishTime() string

GetPublishTime extracts the video publish time.

func (*VideoData) GetRelativeDate

func (vd *VideoData) GetRelativeDate() string

GetRelativeDate extracts the video relative date.

func (*VideoData) GetShortView

func (vd *VideoData) GetShortView() string

GetShortView extracts the video short view count.

func (*VideoData) GetSubscriberCount

func (vd *VideoData) GetSubscriberCount() string

GetDislikeCount extracts the video dislike count.

func (*VideoData) GetTitle

func (vd *VideoData) GetTitle() string

GetTitle returns the title of the video.

func (*VideoData) GetUrl

func (vd *VideoData) GetUrl() string

GetUrl constructs the full URL for the video.

func (*VideoData) GetUrlSuffix

func (vd *VideoData) GetUrlSuffix() string

GetUrlSuffix extracts the video URL suffix.

func (*VideoData) GetUrlThumbnail

func (vd *VideoData) GetUrlThumbnail() string

GetThumbnail retrieves the first thumbnail URL from the list of thumbnails associated with the video.

func (*VideoData) GetViews

func (vd *VideoData) GetViews() string

GetViews extracts the video view count.

func (*VideoData) ID

func (vd *VideoData) ID() string

GetID extracts the video ID.

type VideoPrimaryInfoRenderer

type VideoPrimaryInfoRenderer struct {
	Title            Title        `json:"title"`
	ViewCount        ViewCount    `json:"viewCount"`
	VideoActions     VideoActions `json:"videoActions"`
	DateText         SimpleText   `json:"dateText"`
	RelativeDateText SimpleText   `json:"relativeDateText"`
}

VideoPrimaryInfoRenderer holds primary information about a video.

type VideoSecondaryInfoRenderer

type VideoSecondaryInfoRenderer struct {
	Owner                 Owner       `json:"owner"`
	AttributedDescription Description `json:"attributedDescription"`
}

VideoSecondaryInfoRenderer holds secondary information about a video.

type ViewCount

type ViewCount struct {
	VideoViewCountRenderer struct {
		ViewCount      SimpleText `json:"viewCount"`
		ShortViewCount SimpleText `json:"shortViewCount"`
	} `json:"videoViewCountRenderer"`
}

ViewCount represents the view count of a video.

type ViewCountText

type ViewCountText struct {
	SimpleText string `json:"simpleText"`
}

ViewCountText represents the simple text for the video's view count.

Directories

Path Synopsis
examples
getInfo command
search command

Jump to

Keyboard shortcuts

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