-
Notifications
You must be signed in to change notification settings - Fork 3
/
app_download.go
114 lines (93 loc) · 2.56 KB
/
app_download.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package application
import (
"errors"
"fmt"
"io"
"time"
"github.com/fatih/color"
"github.com/fatih/set"
"github.com/tympanix/supper/list"
"github.com/tympanix/supper/parse"
"github.com/tympanix/supper/types"
"github.com/urfave/cli"
"golang.org/x/text/language"
"golang.org/x/text/language/display"
)
var green = color.New(color.FgGreen)
var red = color.New(color.FgRed)
var yellow = color.New(color.FgYellow)
// DownloadSubtitles downloads subtitles for a whole list of mediafiles for every
// langauge in the language set. Any output is written to the ourpur writer
func (a *Application) DownloadSubtitles(media types.LocalMediaList, lang set.Interface, out io.Writer) (int, error) {
numsubs := 0
dry := a.Context().GlobalBool("dry")
hi := a.Context().GlobalBool("impaired")
score := a.Context().GlobalInt("score")
force := a.Context().GlobalBool("force")
delay, err := parse.Duration(a.Context().GlobalString("delay"))
if err != nil {
return 0, errors.New("could not parse delay time format")
}
// Iterate all media files found in each path
for i, item := range media.List() {
cursubs, err := item.ExistingSubtitles()
if err != nil {
return -1, cli.NewExitError(err, 2)
}
var missingLangs set.Interface
if !force {
missingLangs = set.Difference(lang, cursubs.LanguageSet())
if missingLangs.Size() == 0 {
continue
}
} else {
missingLangs = lang
}
fmt.Fprintf(out, "(%v/%v) - %s\n", i+1, media.Len(), item)
subs := list.RatedSubtitles(item)
if !dry {
search, err := a.SearchSubtitles(item)
if err != nil {
return -1, cli.NewExitError(err, 2)
}
for _, s := range search {
subs.Add(s)
}
}
subs = subs.HearingImpaired(hi)
// Download subtitle for each language
for _, l := range missingLangs.List() {
if delay > 0 {
time.Sleep(delay)
}
l, ok := l.(language.Tag)
if !ok {
return -1, cli.NewExitError(err, 3)
}
langsubs := subs.FilterLanguage(l)
if langsubs.Len() == 0 && !dry {
red.Fprintln(out, " - no subtitles found")
continue
}
if !dry {
sub, best := langsubs.Best()
if best < (float32(score) / 100.0) {
yellow.Fprintf(out, " - score too low %.0f%%\n", best*100.0)
continue
}
onl, ok := sub.(types.OnlineSubtitle)
if !ok {
panic("subtitle could not be cast to online subtitle")
}
err := item.SaveSubtitle(onl, onl.Language())
if err != nil {
red.Fprintln(out, err.Error())
continue
}
numsubs++
}
green.Fprintf(out, " - %v\n", display.English.Languages().Name(l))
}
}
return numsubs, nil
}