-
Notifications
You must be signed in to change notification settings - Fork 0
/
showrunner.go
executable file
·282 lines (246 loc) · 7.53 KB
/
showrunner.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/// 2>/dev/null ; gorun "$0" "$@" ; exit $?
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"github.com/fatih/color"
"github.com/joho/godotenv"
"github.com/urfave/cli/v2"
)
type Episodes struct {
AirDate string `json:"air_date"`
EpisodeNumber int `json:"episode_number"`
Crew []struct {
Job string `json:"job"`
Department string `json:"department"`
CreditID string `json:"credit_id"`
Adult bool `json:"adult"`
Gender int `json:"gender"`
ID int `json:"id"`
KnownForDepartment string `json:"known_for_department"`
Name string `json:"name"`
OriginalName string `json:"original_name"`
Popularity float64 `json:"popularity"`
ProfilePath interface{} `json:"profile_path"`
} `json:"crew"`
GuestStars []struct {
Character string `json:"character"`
CreditID string `json:"credit_id"`
Order int `json:"order"`
Adult bool `json:"adult"`
Gender int `json:"gender"`
ID int `json:"id"`
KnownForDepartment string `json:"known_for_department"`
Name string `json:"name"`
OriginalName string `json:"original_name"`
Popularity float64 `json:"popularity"`
ProfilePath string `json:"profile_path"`
} `json:"guest_stars"`
ID int `json:"id"`
Name string `json:"name"`
Overview string `json:"overview"`
ProductionCode string `json:"production_code"`
SeasonNumber int `json:"season_number"`
StillPath string `json:"still_path"`
VoteAverage float64 `json:"vote_average"`
VoteCount int `json:"vote_count"`
}
type TVShow struct {
_ID string `json:"_id"`
AirDate string `json:"air_date"`
Episodes []Episodes `json:"episodes"`
Name string `json:"name"`
Overview string `json:"overview"`
ID int `json:"id"`
PosterPath string `json:"poster_path"`
SeasonNumber int `json:"season_number"`
}
type EpisodeNames struct {
Name string `json:"name"`
CurrentFilename string `json:"currentFilename"`
NewFilename string `json:"newFilename"`
}
var BuildVersion string = "1.0.0"
// get TMDB data for show
func showData(id string, season string) TVShow {
// get TMDB API key
envPath := os.Getenv("GOPATH") + "/.env.showrunner"
err := godotenv.Load(envPath)
if err != nil {
println(color.RedString("[Error (godotenv.Load)]:"))
log.Fatal(err)
}
// get the show data
key := os.Getenv("TMDB_KEY")
if key == "" {
println(color.RedString("[Error (os.Getenv)]:"))
log.Fatalln("Please provide a TMDB API key")
}
url := "https://api.themoviedb.org/3/tv/" + id + "/season/" + season + "?api_key=" + key
resp, err := http.Get(url)
if err != nil {
println(color.RedString("[Error (http.Get)]:"))
log.Fatal(err)
}
// read the response
rest, err := io.ReadAll(resp.Body)
if err != nil {
println(color.RedString("[Error (io.ReadAll)]:"))
log.Fatal(err)
}
// unmarshal the response
var show TVShow
err = json.Unmarshal(rest, &show)
if err != nil {
println(color.RedString("[Error (json.Unmarshal)]:"))
log.Fatal(err)
}
return show
}
// add zero to single digit season/episode numbers
func addZero(num int) string {
if num < 10 {
return "0" + strconv.Itoa(num)
} else {
return strconv.Itoa(num)
}
}
// get formatted episode names
func episodeNames(data TVShow, showName string) []EpisodeNames {
var episodeName []EpisodeNames
for i := 0; i < len(data.Episodes); i++ {
episode := data.Episodes[i]
// setup match patterns
partPat := regexp.MustCompile(`Part\s([0-9]+):\s`)
spacePat := regexp.MustCompile(`\s+`)
dashPat := regexp.MustCompile(`\s-\s`)
// clean names with parts
name := partPat.ReplaceAllString(episode.Name, `Part $1 - `)
// remove symbols and replace spaces with dashes
fmtPart := partPat.ReplaceAllString(episode.Name, `-Part_$1-`)
fmtSymbols := regexp.MustCompile(`[,:!@#$%^&*()_+{}|\[\]~;’‘'”“"<>?/]`).ReplaceAllString(fmtPart, ``)
fmtName4 := regexp.MustCompile(`\.{3}`).ReplaceAllString(fmtSymbols, ``)
fmtName3 := regexp.MustCompile(`\s--\s`).ReplaceAllString(fmtName4, `-`)
fmtName2 := regexp.MustCompile(`\.\s`).ReplaceAllString(fmtName3, `_`)
fmtName1 := dashPat.ReplaceAllString(fmtName2, `-`)
fmtName := spacePat.ReplaceAllString(fmtName1, `_`)
// generate new filename
cleanName := spacePat.ReplaceAllString(showName, `_`)
cleanerName := dashPat.ReplaceAllString(cleanName, `-`)
file := cleanerName + "-S" + addZero(data.SeasonNumber) + "E" + addZero(episode.EpisodeNumber)
episodeName = append(episodeName, EpisodeNames{
Name: name,
CurrentFilename: file + ".mkv",
NewFilename: file + "-" + fmtName + ".mkv",
})
}
return episodeName
}
// rename file with episode name
func renameFile(episode EpisodeNames) {
log.Println(color.YellowString("[Rename]: ") + episode.CurrentFilename + " -> " + episode.NewFilename)
// rename the file
err := os.Rename(episode.CurrentFilename, episode.NewFilename)
if err != nil {
println(color.RedString("[Error (os.Rename)]:"))
log.Fatal(err)
}
}
// add media title to filename
func setMediaTitle(episode EpisodeNames) {
log.Println(color.YellowString("[mkvpropedit]: ") + "title = " + episode.Name)
// get current direcotry
path, err := os.Getwd()
if err != nil {
println(color.RedString("[Error (os.Getwd)]:"))
log.Fatal(err)
}
// add file metadata
filepath := path + "/" + episode.CurrentFilename
title := "title=" + "\"" + episode.Name + "\""
cmd := exec.Command("mkvpropedit", filepath, "-e", "info", "-s", title)
out, err := cmd.CombinedOutput()
if err != nil {
println(color.RedString("[Error (cmd.CombinedOutput)]:"))
log.Fatal(err)
}
log.Println(color.YellowString("[mkvpropedit]: "), string(out))
}
func addMetadata(showName string, season string, showID string) {
// get the show data
show := showData(showID, season)
newData := episodeNames(show, showName)
// add metadata to files
for i := 0; i < len(newData); i++ {
setMediaTitle(newData[i])
renameFile(newData[i])
}
}
func main() {
var showName string
var season string
var showID string
// versioning
cli.VersionFlag = &cli.BoolFlag{
Name: "version",
Aliases: []string{"v"},
Usage: "print app version",
}
// help
cli.AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
VERSION:
{{.Version}}
USAGE:
{{.HelpName}} [optional options]
OPTIONS:
{{range .VisibleFlags}} {{.}}{{ "\n" }}{{end}}
`
cli.HelpFlag = &cli.BoolFlag{
Name: "help",
Aliases: []string{"h"},
Usage: "show help",
}
// execute app
app := &cli.App{
Name: "showrunner",
Usage: "Add episode metadata to shows from TMDB",
Version: BuildVersion,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "showName",
Aliases: []string{"n"},
Usage: "show name (spaces are allowed)",
Destination: &showName,
Required: true,
},
&cli.StringFlag{
Name: "season",
Aliases: []string{"s"},
Usage: "show seaon",
Destination: &season,
Required: true,
},
&cli.StringFlag{
Name: "showID",
Aliases: []string{"i"},
Usage: "TMDB show id",
Destination: &showID,
Required: true,
},
},
Action: func(*cli.Context) error {
addMetadata(showName, season, showID)
return nil
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}