/
search.go
87 lines (73 loc) · 1.93 KB
/
search.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"flag"
"fmt"
"log"
"net/url"
"strings"
"github.com/jangler/minipkg/tool"
)
var flagSearchN uint = 1
var flagSearchType = "video,channel,playlist"
type searchID struct {
Kind, VideoID, PlaylistID string
}
type searchSnippet struct {
ChannelTitle string
}
type searchItem struct {
ID searchID
Snippet searchSnippet
}
type searchResponse struct {
Items []searchItem
}
func search(args []string) {
if flagSearchN > 50 {
log.Fatal("-n option must be in the range [0, 50]")
}
query := strings.Join(args, " ")
addr := fmt.Sprintf(
"%s/search?key=%s&part=snippet&maxResults=%d&q=%s&type=%s",
apiRoot, apiKey, flagSearchN, url.QueryEscape(query),
url.QueryEscape(flagSearchType))
var v searchResponse
decodeResponse(addr, &v)
for _, item := range v.Items {
switch item.ID.Kind {
case "youtube#channel":
fmt.Printf("https://www.youtube.com/user/%s\n",
item.Snippet.ChannelTitle)
case "youtube#playlist":
fmt.Printf("https://www.youtube.com/playlist?list=%s\n",
item.ID.PlaylistID)
case "youtube#video":
fmt.Printf("https://www.youtube.com/watch?v=%s\n", item.ID.VideoID)
default:
fmt.Printf("Unknown item type: %s\n", item.ID.Kind)
}
}
}
func init() {
cmd := &tool.Command{
Name: "search",
Summary: "print the URLs of resources matching a query",
Usage: "[<option>]... <query>...",
Description: `
Search YouTube for <query> (joined by spaces if multiple arguments are
given) and print the URLs of the top matches in descending order by
relevance.
`,
Function: search,
MinArgs: 1,
MaxArgs: -1,
HasOpts: true,
}
cmd.FlagSet = flag.NewFlagSet(cmd.Name, flag.ExitOnError)
cmd.FlagSet.Usage = tool.UsageFunc(cmd)
cmd.FlagSet.UintVar(&flagSearchN, "n", flagSearchN,
"maximum number of results, in the range [0, 50]")
cmd.FlagSet.StringVar(&flagSearchType, "type", flagSearchType,
"restrict search to given resource types")
tool.Commands[cmd.Name] = cmd
}