Skip to content

Commit

Permalink
Fix using search when yt video is a link
Browse files Browse the repository at this point in the history
  • Loading branch information
fakelag committed Feb 18, 2024
1 parent 78dcafe commit 8af210d
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions youtubeapi/youtube.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"math/rand"
"net/url"
"os/exec"
"regexp"
"strconv"
Expand Down Expand Up @@ -81,12 +82,14 @@ func (yt *Youtube) GetYoutubeMedia(videoIdOrSearchTerm string) (*YoutubeMedia, e
return nil, err
}

useSearch := true

videoArg := videoIdOrSearchTerm

if useSearch {
videoID := getYoutubeUrlVideoId(videoIdOrSearchTerm)

if videoID == "" {
videoArg = "ytsearch:" + videoIdOrSearchTerm
} else {
videoArg = "https://www.youtube.com/watch?v=" + videoID
}

replacer := strings.NewReplacer(
Expand Down Expand Up @@ -286,6 +289,28 @@ func NewYoutubePlaylist(
return pl
}

func getYoutubeUrlVideoId(urlString string) string {
parsedUrl, err := url.Parse(urlString)

if err != nil {
return ""
}

if !strings.Contains(parsedUrl.Hostname(), "youtube") && !strings.Contains(parsedUrl.Hostname(), "youtu.be") {
return ""
}

rx := regexp.MustCompile("^.*(?:(?:youtu\\.be\\/|v\\/|vi\\/|u\\/\\w\\/|embed\\/|shorts\\/)|(?:(?:watch)?\\?v(?:i)?=|\\&v(?:i)?=))([^#\\&\\?]*).*")

results := rx.FindStringSubmatch(urlString)

if len(results) >= 2 {
return results[1]
}

return ""
}

func getYtDlpPath() (string, error) {
path, err := exec.LookPath("yt-dlp")

Expand Down

0 comments on commit 8af210d

Please sign in to comment.