-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
268 lines (240 loc) · 7.04 KB
/
main.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
package main
import (
"bufio"
"bytes"
"crypto/md5"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/1lann/promptui" // using this instead of manifoldco because of race conditions and weird bugs 🤷♂️
)
//go:embed template.gohtml
var templateHTML string
//go:embed js/main.js
var mainScript string
//go:embed js/body.js
var bodyScript string
var version = "DEV"
// UserAnswers holds config answers from command line prompt ui
type UserAnswers struct {
MediaFolder string
MediaFiles []string
PlayOnlyOne bool
LoopFirstVideo bool
HaveTransitionVideo bool
TransitionVideo string
HashKey string
}
// Scripts stores javascript scripts that are later injected into templateHTML
type Scripts struct {
MainScript string
BodyScript string
}
var scripts = Scripts{
MainScript: mainScript,
BodyScript: bodyScript,
}
var (
outputHTMLName = "obs-random-videos.html"
audioFileExts = []string{".mp3", ".ogg", ".aac"}
videoFileExts = []string{".mp4", ".webm", ".mpeg4", ".m4v", ".mov"}
// imagesFileExts = []string{".png", ".jpg", ".jpeg", ".gif", ".webp"}
// mediaFileExts = append(append(audioFileExts, videoFileExts...), imagesFileExts...)
mediaFileExts = append(audioFileExts, videoFileExts...)
promptDelay = 100 * time.Millisecond // helps with race conditions in promptui
)
func main() {
fmt.Printf("OBS Random Video: %s\n\n", version)
mainDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("Failed to get current directory path: %v", err)
}
mediaFiles := getMediaFiles(mainDir)
if len(mediaFiles) < 1 {
fmt.Printf("No media files found in: %s", mainDir)
fmt.Print("\n\nPress enter to exit...")
input := bufio.NewScanner(os.Stdin)
input.Scan()
return
}
answers, err := askQuestions(mediaFiles, mainDir)
if err != nil {
log.Fatalf("Something went wrong getting user input: %v", err)
}
if answers.TransitionVideo != "" {
answers.MediaFiles = removeTransitionVideo(answers.TransitionVideo, answers.MediaFiles)
}
templateHTML = "<!--\nOBS Random Videos: " + version + "\nAUTO GENERATED FILE\nDON'T TOUCH\n-->\n" + templateHTML
var outputHTML bytes.Buffer
t := template.Must(template.New("HTML").Parse(templateHTML))
err = t.Execute(&outputHTML, scripts)
if err != nil {
log.Fatalf("Failed compiling template: %v", err)
}
t = template.Must(template.New("HTML").Funcs(template.FuncMap{"StringsJoin": strings.Join}).Parse(outputHTML.String()))
outputHTML.Reset()
err = t.Execute(&outputHTML, answers)
if err != nil {
log.Fatalf("Failed compiling template final: %v", err)
}
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
outputHTMLFilePath := filepath.Join(exPath, outputHTMLName)
outputHTMLFile, err := os.Create(outputHTMLFilePath)
if err != nil {
log.Fatalf("Failed create output file: %v", err)
}
outputHTMLFile.WriteString(outputHTML.String())
outputHTMLFile.Close()
os.Exit(0)
}
func getMediaFiles(currentDir string) []string {
mediaFiles := []string{}
filepath.WalkDir(currentDir, func(path string, file fs.DirEntry, err error) error {
if err != nil {
return err
}
if !file.IsDir() {
if isValidFileType(file) {
// TODO: move this fix to end of program before injection
// Then clean up getTransitionVideo and show the subpath in the file selector
fixedFilePath := fixFilePath(path)
mediaFiles = append(mediaFiles, fixedFilePath)
}
}
return nil
})
return mediaFiles
}
func fixFilePath(filePath string) string {
separator := string(os.PathSeparator)
if separator != "/" {
return strings.Replace(filePath, separator, "/", -1)
}
return filePath
}
func askQuestions(mediaFiles []string, mainDir string) (UserAnswers, error) {
answers := UserAnswers{
MediaFiles: mediaFiles,
PlayOnlyOne: false,
LoopFirstVideo: false,
HaveTransitionVideo: false,
TransitionVideo: "",
HashKey: "",
}
answers.PlayOnlyOne = showQuestion("Do you only want to play one video? (The first random video will play once and then stop)", false)
if !answers.PlayOnlyOne {
answers.LoopFirstVideo = showQuestion("Do you want to loop the first video?", false)
answers.HaveTransitionVideo = showQuestion("Do have a transition video? (This video plays after every other video)", false)
if answers.HaveTransitionVideo {
err := errors.New("")
answers.TransitionVideo, err = getTransitionVideo(mediaFiles, mainDir)
if err != nil {
return answers, err
}
}
}
answers.HashKey = createHashFromUserAnswers(answers)
return answers, nil
}
func createHashFromUserAnswers(answers UserAnswers) string {
s := fmt.Sprintf(
"%v%v%v%s%s",
answers.PlayOnlyOne,
answers.LoopFirstVideo,
answers.HaveTransitionVideo,
answers.TransitionVideo,
strings.Join(answers.MediaFiles[:], ""))
// deepcode ignore InsecureHash: Not using this hash for anything sensitive
hasher := md5.New()
hasher.Write([]byte(s))
return hex.EncodeToString(hasher.Sum(nil))
}
func removeTransitionVideo(transitionVideo string, mediaFiles []string) []string {
files := mediaFiles
for i, file := range mediaFiles {
if file == transitionVideo {
files[i] = files[len(files)-1]
return files[:len(files)-1]
}
}
return files
}
func isValidFileType(file fs.DirEntry) bool {
fileExts := mediaFileExts
for _, ext := range fileExts {
if strings.HasSuffix(file.Name(), ext) {
return true
}
}
return false
}
func getTransitionVideo(mediaFiles []string, mainDir string) (string, error) {
items := []string{}
// Strip full filepath when displaying options to users
for _, filePath := range mediaFiles {
fileParts := strings.Split(filePath, string(os.PathSeparator))
fmt.Printf("%v", fileParts)
fileName := fileParts[len(fileParts)-1]
items = append(items, fileName)
}
items = append(items, "CANCEL")
prompt := promptui.Select{
Label: "Select your transition video",
Items: items,
}
_, result, err := prompt.Run()
time.Sleep(promptDelay)
if err != nil {
return "", err
}
if strings.ToLower(result) != "cancel" {
// Need to match file name with full path again
for _, filePath := range mediaFiles {
if strings.Contains(filePath, result) {
return filePath, nil
}
}
log.Fatalf("Error occurred when trying to get transition video path for: %s", result)
}
return "", nil
}
func showQuestion(message string, defaultValueFlag bool) bool {
defaultValue := "y"
if !defaultValueFlag {
defaultValue = "n"
}
allowedValues := [...]string{"y", "yes", "no", "n"}
validate := func(input string) error {
for _, value := range allowedValues {
if strings.ToLower(input) == value {
return nil
}
}
return fmt.Errorf("number should be one of the values %v", allowedValues)
}
prompt := promptui.Prompt{
Label: message,
Validate: validate,
Default: defaultValue,
}
result, err := prompt.Run()
if err != nil {
time.Sleep(promptDelay)
return showQuestion(message, defaultValueFlag)
}
result = strings.ToLower(result)
time.Sleep(promptDelay)
return result == "y" || result == "yes"
}