/
movie_search.go
80 lines (57 loc) · 1.79 KB
/
movie_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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"github.com/olekukonko/tablewriter"
"gitlab.com/haath/goirate/pkg/movies"
)
// MovieSearchCommand is the command used to search for movies on IMDb.
type MovieSearchCommand struct {
Year uint16 `short:"y" long:"year" description:"The release year to limit the movie search to."`
Count uint `short:"c" long:"count" description:"Limit the number of results."`
Args positionalArgs `positional-args:"1" required:"1"`
}
// Execute is the callback of the movie command.
func (c *MovieSearchCommand) Execute(args []string) error {
var searchResult []movies.MovieID
var err error
omdb := Config.OMDBCredentials
if omdb.IsEnabled() {
searchResult, err = omdb.Search(c.Args.Query)
} else {
// No OMDb API key provided, fall back to IMDb.
searchResult, err = movies.Search(c.Args.Query)
}
if err != nil {
return err
}
if c.Count > 0 && uint(len(searchResult)) > c.Count {
searchResult = searchResult[:c.Count]
}
if Options.JSON {
moviesJSON, err := json.MarshalIndent(searchResult, "", " ")
if err != nil {
return err
}
log.Println(string(moviesJSON))
} else {
log.Printf(getMoviesTable(searchResult))
}
return nil
}
func getMoviesTable(movies []movies.MovieID) string {
buf := bytes.NewBufferString("")
table := tablewriter.NewWriter(buf)
table.SetHeader([]string{"IMDb ID", "Title", "Year"})
table.SetColumnAlignment([]int{tablewriter.ALIGN_DEFAULT, tablewriter.ALIGN_CENTER, tablewriter.ALIGN_DEFAULT})
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.SetAutoFormatHeaders(false)
for _, movie := range movies {
table.Append([]string{movie.IMDbID, movie.Title, fmt.Sprint(movie.Year)})
}
table.Render()
return buf.String()
}