-
Notifications
You must be signed in to change notification settings - Fork 20
/
get.go
84 lines (76 loc) · 1.87 KB
/
get.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
package cmd
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"github.com/h2non/filetype"
"github.com/oz/osdb"
"github.com/spf13/cobra"
)
var NoSub = errors.New("No subtitles found!")
func init() {
getCmd.Flags().StringVarP(¶mLang, "lang", "l", GetEnvLang(), "Subtitle language")
RootCmd.AddCommand(getCmd)
}
var getCmd = &cobra.Command{
Use: "get [file/directory]",
Short: "Get subtitles for a file or for all files in a directory.",
Long: `Download subtitles for a file or for all files in a directory.`,
Run: func(cmd *cobra.Command, args []string) {
for _, l := range paramLangs {
client, err := InitClient(l)
if err != nil {
fmt.Printf("Error: %s\n", err)
}
if len(args) == 1 {
x, err := os.Stat(args[0])
if err != nil {
fmt.Printf("Error: %s\n", err)
break
} else if x.IsDir() {
args = getFilesFromPath(args[0])
}
}
for _, file := range args {
if err := getSubs(client, file, l); err != nil {
if err != NoSub {
fmt.Printf("Error: %s\n", err)
return
}
fmt.Println(err)
continue
} else {
return
}
}
}
},
}
func getSubs(client *osdb.Client, file string, lang string) error {
fmt.Printf("- Getting %s subtitles for file: %s\n", lang, path.Base(file))
subs, err := client.FileSearch(file, []string{lang})
if err != nil {
return err
}
if best := subs.Best(); best != nil {
dest := file[0:len(file)-len(path.Ext(file))] + ".srt"
fmt.Printf("- Downloading to: %s\n", dest)
// XXX check if dest exists instead of overwriting?
return client.DownloadTo(best, dest)
}
return NoSub
}
func getFilesFromPath(dir string) []string {
files := []string{}
entries, _ := ioutil.ReadDir(dir)
for _, e := range entries {
file := path.Join(dir, e.Name())
buf, _ := ioutil.ReadFile(file)
if filetype.IsVideo(buf) {
files = append(files, file)
}
}
return files
}