aboutsummaryrefslogtreecommitdiff
path: root/youtube.go
blob: 5b97e50da738b1d5edad2ffc5b7802e006518cea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main

import (
	"encoding/json"
	"fmt"
	"muhq.space/go/wrms/llog"
	"os/exec"
	"strings"
)

type YoutubeBackend struct {
	searchResults int
}

func NewYoutubeBackend() *YoutubeBackend {
	return &YoutubeBackend{10}
}

func (_ *YoutubeBackend) OnSongFinished(*Song) {}

func (_ *YoutubeBackend) Play(song *Song, player Player) {
	player.PlayUri("https://youtube.com/watch?v=" + song.Uri)
}

type YoutubeDlSearchResult struct {
	Id    string
	Title string
}

func (b *YoutubeBackend) Search(patterns map[string]string) []*Song {
	pattern := ""
	for _, v := range patterns {
		pattern += v + " "
	}

	searchOption := fmt.Sprintf("ytsearch%d:%s", b.searchResults, pattern[:len(pattern)-1])
	llog.Debug("Search youtube using: youtube-dl -j %s", searchOption)
	results, err := exec.Command("yt-dlp", "-j", searchOption).Output()

	if err != nil {
		llog.Error("youtube-dl failed with: %s", err)
	}

	songs := []*Song{}
	for _, l := range strings.Split(string(results), "\n") {
		if l == "" {
			continue
		}

		result := YoutubeDlSearchResult{}
		err = json.Unmarshal([]byte(l), &result)
		if err != nil {
			llog.Debug("Parsing youtube-dl results '%s' failed", l)
			llog.Error("Parsing youtube-dl results failed with: %s", err)
		}
		songs = append(songs, NewSong(result.Title, "", "youtube", result.Id))
	}

	llog.Debug("youtube found %d matching videos", len(songs))
	return songs
}