-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
237 lines (201 loc) · 6.28 KB
/
main.go
File metadata and controls
237 lines (201 loc) · 6.28 KB
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
// main.go
// Copyright (C) 2024 Ricardo Melo
//
// Distributed under terms of the MIT license.
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/andreykaipov/goobs"
"github.com/andreykaipov/goobs/api/requests/scenes"
)
// Config holds the application configuration
type Config struct {
host string
port string
password string
passwordFile string
passwordProvided bool // true if password was explicitly provided via -password flag
scene1 string
scene2 string
timeout time.Duration
verbose bool
}
var osExit = os.Exit
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
// Initialize logging
log.SetFlags(log.LstdFlags | log.Lshortfile)
// Parse configuration
config := parseFlags()
if config.verbose {
log.Printf("Connecting to OBS at %s:%s\n", config.host, config.port)
log.Printf("Switching between scenes: %s and %s\n", config.scene1, config.scene2)
}
// Create and configure client
client, err := createClient(config)
if err != nil {
// If connection failed and no password was explicitly provided,
// try reading from password file as a fallback
if !config.passwordProvided && config.password == "" && config.passwordFile != "" {
if config.verbose {
log.Printf("Initial connection failed, attempting with password from file...")
}
filePassword, readErr := readPasswordFromFile(config.passwordFile)
if readErr == nil && filePassword != "" {
config.password = filePassword
if config.verbose {
log.Printf("Retrying connection with password from: %s", config.passwordFile)
}
client, err = createClient(config)
}
}
if err != nil {
log.Fatalf("Failed to connect to OBS: %v", err)
}
}
defer client.Disconnect()
if err := switchScene(client, config); err != nil {
log.Fatalf("Failed to switch scene: %v", err)
}
}
// readPasswordFromFile reads and returns the password from a file
func readPasswordFromFile(filePath string) (string, error) {
// Expand home directory if path starts with ~/
if strings.HasPrefix(filePath, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get home directory: %w", err)
}
filePath = filepath.Join(home, filePath[2:])
}
// Check if file exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return "", nil // File doesn't exist, return empty password
}
// Read the file
content, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("failed to read password file: %w", err)
}
// Trim whitespace and newlines
password := strings.TrimSpace(string(content))
return password, nil
}
// parseFlags handles command-line argument parsing and validation
func parseFlags() Config {
config := Config{}
var password string
// Add version flag
showVersion := flag.Bool("version", false, "Show version information")
flag.StringVar(&config.host, "host", "localhost", "OBS WebSocket host")
flag.StringVar(&config.port, "port", "4455", "OBS WebSocket port")
flag.StringVar(&password, "password", "", "OBS WebSocket password")
flag.StringVar(&config.passwordFile, "password-file", "~/.obspwd", "Path to file containing OBS WebSocket password")
flag.DurationVar(&config.timeout, "timeout", 5*time.Second, "Connection timeout")
flag.BoolVar(&config.verbose, "verbose", false, "Enable verbose logging")
// Custom usage message
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] <scene1> <scene2>\n\nOptions:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
// Check if version flag was set
if *showVersion {
fmt.Printf("obs_switchscene %s (commit: %s, built at: %s)\n", version, commit, date)
osExit(0)
}
// Validate positional arguments
args := flag.Args()
if len(args) != 2 {
flag.Usage()
osExit(1)
}
config.scene1 = args[0]
config.scene2 = args[1]
// Track if password was explicitly provided
config.passwordProvided = password != ""
config.password = password
// Handle password: command-line takes precedence over file
if config.password == "" && config.passwordFile != "" {
filePassword, err := readPasswordFromFile(config.passwordFile)
if err != nil {
log.Printf("Warning: %v", err)
} else if filePassword != "" {
config.password = filePassword
if config.verbose {
log.Printf("Using password from file: %s", config.passwordFile)
}
}
}
return config
}
// createClient creates and configures an OBS WebSocket client with timeout
func createClient(config Config) (*goobs.Client, error) {
connectionChan := make(chan struct {
client *goobs.Client
err error
}, 1)
go func() {
client, err := goobs.New(
config.host+":"+config.port,
goobs.WithPassword(config.password),
)
connectionChan <- struct {
client *goobs.Client
err error
}{client, err}
}()
select {
case <-time.After(config.timeout):
return nil, fmt.Errorf("connection timeout after %v", config.timeout)
case result := <-connectionChan:
return result.client, result.err
}
}
// switchScene handles the scene switching logic
func switchScene(client *goobs.Client, config Config) error {
// Get current scene
currentSceneResp, err := client.Scenes.GetCurrentProgramScene()
if err != nil {
return fmt.Errorf("failed to get current scene: %w", err)
}
currentScene := currentSceneResp.CurrentProgramSceneName
// Get scene list to validate both scenes exist
sceneListResp, err := client.Scenes.GetSceneList()
if err != nil {
return fmt.Errorf("failed to get scene list: %w", err)
}
// Validate that both scenes exist
sceneMap := make(map[string]bool)
for _, scene := range sceneListResp.Scenes {
sceneMap[scene.SceneName] = true
}
if !sceneMap[config.scene1] || !sceneMap[config.scene2] {
return fmt.Errorf("one or both scenes do not exist: %s, %s", config.scene1, config.scene2)
}
// Determine which scene to switch to
targetScene := config.scene1
if currentScene == config.scene1 {
targetScene = config.scene2
}
// Switch scene
if config.verbose {
log.Printf("Switching from scene '%s' to scene: '%s'\n", currentScene, targetScene)
}
params := scenes.NewSetCurrentProgramSceneParams().WithSceneName(targetScene)
_, err = client.Scenes.SetCurrentProgramScene(params)
if err != nil {
return fmt.Errorf("failed to switch scene: %w", err)
}
return nil
}