-
Notifications
You must be signed in to change notification settings - Fork 2
/
sps.go
543 lines (462 loc) · 13.2 KB
/
sps.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
package main // Stream Play Server
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"syscall"
"unsafe"
"time"
"path/filepath"
"strconv"
"bufio"
"unicode/utf16"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetStdHandle = kernel32.NewProc("GetStdHandle")
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
procSetConsoleMode = kernel32.NewProc("SetConsoleMode")
)
var (
moduser32 = syscall.NewLazyDLL("user32.dll")
enumWindowsProc = moduser32.NewProc("EnumWindows")
getWindowTextW = moduser32.NewProc("GetWindowTextW")
isWindowVisible = moduser32.NewProc("IsWindowVisible")
)
const (
stdInputHandle = uint32(-10 & 0xFFFFFFFF)
)
var signCmd *exec.Cmd
var serverCmd *exec.Cmd
var clientCmd *exec.Cmd
var (
ipAddress string
port string
title string
)
/**
* main is the main entry point of the SPS program.
* It reads configuration from a JSON file, launches various processes, and handles user input.
*/
func main() {
args := os.Args[1:] // Exclude the first argument, which is the program name
jsonFile := "config.json"
// Read the JSON file
jsonBytes, err := ioutil.ReadFile(jsonFile)
if err != nil {
log.Fatal(err)
}
// Extract the IP address using string manipulation
jsonStr := string(jsonBytes)
ipAddress = extractFieldValue(jsonStr, `"ip_address"`)
port = extractFieldValue(jsonStr, `"port"`)
if len(args) > 0 && args[0] == "-ui" {
title = ""
} else {
title = extractFieldValue(jsonStr, `"window_name"`)
}
if title == "" {
title = setTitleManually()
if title == "" {
panic(0)
}
}
fmt.Println(ipAddress)
fmt.Println(port)
fmt.Println(title)
// Get the current working directory
workingDir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
// Add Config json file to the webserver
configWebserverPath := filepath.Join(workingDir, "webserver/client/wconfig.json")
// Create the destination file
configWebserverFile, err := os.Create(configWebserverPath)
if err != nil {
log.Fatal(err)
}
defer configWebserverFile.Close()
// Write the content to the destination file
_, err = configWebserverFile.Write(jsonBytes)
if err != nil {
log.Fatal(err)
}
log.Println("Config File copied successfully!")
// Set the folder to be appended to the working directory
folderSign := "signaling"
folderServer := "media-server"
folderWeb := "webserver"
////////////////////////////
// Start signaling server //
////////////////////////////
// Append the folder to the working directory
folderSignPath := filepath.Join(workingDir, folderSign)
// Start signalling server process to generate raw video frames
signCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port,
},
"logs/sign.log",
folderSignPath,
)
if err != nil {
panic(err)
}
// Use a defer statement to ensure the command process is killed when the main function exits
defer func() {
stopProcess(signCmd)
}()
/////////////////////////
// Start WebRTC server //
/////////////////////////
// Append the folder to the working directory
folderServerPath := filepath.Join(workingDir, folderServer)
// Start signalling server process to generate raw video frames
serverCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port, title,
},
"logs/server.log",
folderServerPath,
)
if err != nil {
panic(err)
}
// Use a defer statement to ensure the command process is killed when the main function exits
defer func() {
stopProcess(serverCmd)
}()
/////////////////////
// Start WebServer //
/////////////////////
// Append the folder to the working directory
folderWebPath := filepath.Join(workingDir, folderWeb)
// Start signalling server process to generate raw video frames
clientCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port,
},
"logs/client.log",
folderWebPath,
)
if err != nil {
panic(err)
}
// Use a defer statement to ensure the command process is killed when the main function exits
defer func() {
stopProcess(clientCmd)
}()
// Monitoring with goroutine every 10 sec
go func() {
for {
// Wait for 10 seconds before checking again
time.Sleep(10 * time.Second)
status := "[status]"
if signCmd != nil {
if signCmd.ProcessState != nil && signCmd.ProcessState.Exited() {
status += " sign: off "
} else {
status += " sign: on "
}
}
if serverCmd != nil {
if serverCmd.ProcessState != nil && serverCmd.ProcessState.Exited() {
status += " server: off "
} else {
status += " server: on "
}
}
if clientCmd != nil {
if clientCmd.ProcessState != nil && clientCmd.ProcessState.Exited() {
status += " client: off "
} else {
status += " client: on "
}
}
fmt.Println(status)
}
}();
// Set the terminal to raw mode to capture keypresses immediately
setRawMode()
reader := bufio.NewReader(os.Stdin)
for {
// Read a line of input (including newline characters)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
return
}
line = strings.TrimRight(line, "\r\n")
switch line {
case "exit":
fmt.Println("Stopping SPS...")
return
case "stop":
stopProcess(signCmd)
stopProcess(clientCmd)
stopProcess(serverCmd)
case "sign":
fmt.Println("Restart sign")
stopProcess(signCmd)
signCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port,
},
"logs/sign.log",
folderSignPath,
)
if err != nil {
panic(err)
}
case "client":
fmt.Println("Restart client")
stopProcess(clientCmd)
clientCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port,
},
"logs/client.log",
folderWebPath,
)
if err != nil {
panic(err)
}
case "server":
fmt.Println("Restart server")
stopProcess(serverCmd)
serverCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port, title,
},
"logs/server.log",
folderServerPath,
)
if err != nil {
panic(err)
}
case "change":
title = setTitleManually()
if title == "" {
continue
}
fmt.Println("Restart server")
stopProcess(serverCmd)
serverCmd, err = launchCommand(
"go",
[]string{
"run", ".",
ipAddress, port, title,
},
"logs/server.log",
folderServerPath,
)
if err != nil {
panic(err)
}
default:
// Handle the case when an invalid command is provided.
fmt.Println("Invalid command : " + line)
}
}
}
/**
* extractFieldValue extracts the field value from a JSON string.
*
* @param jsonStr The JSON string to extract the field value from.
* @param field The field name to extract the value for.
* @return The extracted field value as a string.
*/
func extractFieldValue(jsonStr string, field string) string {
startIndex := strings.Index(jsonStr, field)
if startIndex == -1 {
log.Fatalf("Field '%s' not found in JSON", field)
}
startIndex += len(field) + 3 // Adjust start index to skip the field and the following characters `": `
endIndex := strings.Index(jsonStr[startIndex:], `"`)
if endIndex == -1 {
log.Fatalf("Field value not found for '%s'", field)
}
return jsonStr[startIndex : startIndex+endIndex]
}
/**
* setRawMode sets the terminal to raw mode for capturing keypresses immediately.
*/
func setRawMode() {
stdinHandle, _, _ := procGetStdHandle.Call(uintptr(stdInputHandle))
var mode uint32
_, _, _ = procGetConsoleMode.Call(stdinHandle, uintptr(unsafe.Pointer(&mode)))
mode &^= 0x0004 // Disable ECHO
_, _, _ = procSetConsoleMode.Call(stdinHandle, uintptr(mode))
}
/**
* getCurrentDirectory returns the current directory.
*
* @return The current directory as a string.
*/
func getCurrentDirectory() string {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return dir
}
/**
* launchCommand launches a command as a subprocess in a new process group.
*
* @param command The name or path of the executable command to run.
* @param args An array of strings representing the command-line arguments for the executable.
* @param filePath Path of the log file for the process output redirection.
* @param workingDir Directory on which to launch the process.
* @return A pointer to the Cmd struct representing the running command and an error (if any).
* If there is an error while starting the command, the returned pointer will be nil, and the error will be non-nil.
*/
func launchCommand(command string, args []string, filePath string, workingDir string) (*exec.Cmd, error) {
cmd := exec.Command(command, args...)
fmt.Println(cmd)
outFile, err := os.Create(filePath)
if err != nil {
panic(err)
}
defer outFile.Close()
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP}
cmd.Stdout = outFile
cmd.Stderr = outFile
if workingDir != "" {
cmd.Dir = workingDir
}
if err := cmd.Start(); err != nil {
return nil, err
}
// Used to get the process state
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
return cmd, nil
}
/**
* killProcess forcefully terminates a process and its subprocesses on Windows.
*
* @param cmd A pointer to the exec.Cmd struct representing the running command to be terminated.
* @return An error encountered during the termination process. Returns nil if successful.
*/
func killProcess(cmd *exec.Cmd) error {
pgid := -cmd.Process.Pid
killCmd := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(-pgid))
return killCmd.Run()
}
/**
* stopProcess forcefully terminates a process and handles its termination status.
* If the process has already exited, prints a message indicating so.
* If the process is still running, attempts to kill it and prints a message about the action taken.
*
* @param cmd A pointer to the exec.Cmd struct representing the running command to be stopped.
*/
func stopProcess(cmd *exec.Cmd) {
if cmd != nil {
if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
fmt.Println("Process is already stopped")
return
} else {
if cmd.Process != nil {
if err := killProcess(cmd); err != nil {
fmt.Println("Error killing process:", err)
return
}
fmt.Println("Process killed :", cmd)
return
}
}
}
fmt.Println("Should not happen...")
}
/**
* findWindowTitle retrieves the window title of a given executable string.
*
* @param execString The executable string used to identify the window.
* @return The window title as a string if found, or an error if the title is not found.
*/
func findWindowTitle(execString string) (string, error) {
// Run the tasklist command to get the window titles
tasklistCmd := exec.Command("cmd.exe", "/C", "tasklist", "/v", "/fi", "imagename eq " + execString, "/fo", "list", "|", "findstr", "Titre")
output, err := tasklistCmd.Output()
if err != nil {
return "", err
}
// Convert bytes to string
lines := strings.Split(string(output), "\n")
for _, line := range lines {
// Split the windowString using ":" as the delimiter
parts := strings.Split(line, ": ")
if len(parts) > 1 && len(parts[1]) > 0 {
// Need to remove useless byte at the end : [13] => (carriage return)
return parts[1][:len(parts[1])-1], nil
}
}
return "", fmt.Errorf("window title not found")
}
/**
* getWindowTitles retrieves a list of visible window titles.
*
* @return A slice of strings representing the visible window titles.
*/
func getWindowTitles() []string {
var titles []string
enumWindowsProc.Call(syscall.NewCallback(func(hwnd syscall.Handle, lParam uintptr) uintptr {
var buf [256]uint16
if _, _, err := getWindowTextW.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))); err.(syscall.Errno) == 0 {
length := 0
for buf[length] != 0 {
length++
}
title := string(utf16.Decode(buf[:length]))
visible, _, _ := isWindowVisible.Call(uintptr(hwnd))
if visible != 0 && len(title) > 0 {
titles = append(titles, title)
}
}
return 1 // Continue enumeration
}), 0)
return titles
}
/**
* setTitleManually interactively prompts the user to manually select a window title.
*
* @return The selected window title as a string. If the index is invalid, it returns an empty string.
*/
func setTitleManually() string {
titles := getWindowTitles()
fmt.Println("[Window Titles (visible)]")
for i, t := range titles {
fmt.Printf("%d: %s\n", i, t)
}
// Wait for index input after the loop
var index int
index = -1
fmt.Print("Enter the index of the window you want to select: ")
fmt.Scanln(&index)
// Perform further operations based on the selected index
if index >= 0 && index < len(titles) {
fmt.Println("You selected window title:", titles[index])
return titles[index]
} else {
fmt.Println("Invalid index. Please enter a valid index.")
return ""
}
}