112 lines
1.9 KiB
Go
112 lines
1.9 KiB
Go
package shell
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
|
|
"github.com/urfave/cli/v2"
|
|
"gitnet.fr/deblan/mu-go/internal/api"
|
|
"gitnet.fr/deblan/mu-go/internal/cmd"
|
|
"gitnet.fr/deblan/mu-go/internal/render"
|
|
)
|
|
|
|
type Shell struct {
|
|
Name string
|
|
Order string
|
|
Directory string
|
|
ApiUrl string
|
|
}
|
|
|
|
func NewShell(name, order, directory, apiUrl string) *Shell {
|
|
return &Shell{
|
|
Name: name,
|
|
Order: order,
|
|
Directory: directory,
|
|
ApiUrl: strings.TrimSuffix(apiUrl, "/"),
|
|
}
|
|
}
|
|
|
|
func (s *Shell) Prompt(defaultValue string) string {
|
|
reader := bufio.NewReader(os.Stdin)
|
|
|
|
fmt.Printf("> [%s] ", defaultValue)
|
|
input, _ := reader.ReadString('\n')
|
|
input = strings.Replace(input, "\n", "", -1)
|
|
|
|
if input == "" {
|
|
input = defaultValue
|
|
}
|
|
|
|
return input
|
|
}
|
|
|
|
func (s *Shell) Run(action string, args cli.Args) error {
|
|
directory := strings.TrimSuffix(s.Directory, "/")
|
|
|
|
files := api.RequestFileList(
|
|
s.ApiUrl,
|
|
s.Name,
|
|
s.Order,
|
|
)
|
|
|
|
input := strings.Trim(args.Get(0), " ")
|
|
|
|
switch input {
|
|
case "":
|
|
render.RenderFiles(files)
|
|
input = s.Prompt("1")
|
|
case "q":
|
|
return nil
|
|
}
|
|
|
|
files = files.Select(input)
|
|
|
|
if files.Empty() {
|
|
fmt.Println("Empty list, aborded!")
|
|
return nil
|
|
}
|
|
|
|
var commands []*exec.Cmd
|
|
|
|
switch action {
|
|
case "play":
|
|
commands = append(commands, cmd.PlayerCmd(files))
|
|
case "download":
|
|
commands = cmd.DownloadCmds(files, directory)
|
|
}
|
|
|
|
s.ExecCommands(commands)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Shell) ExecCommands(commands []*exec.Cmd) {
|
|
for _, cmd := range commands {
|
|
fmt.Printf("<----->\nCommand: %s\n<----->\n", cmd)
|
|
|
|
stdout, _ := cmd.StdoutPipe()
|
|
scanner := bufio.NewScanner(stdout)
|
|
|
|
cmd.Start()
|
|
|
|
for scanner.Scan() {
|
|
out := fmt.Sprintf("%q", scanner.Text())
|
|
out = strings.Trim(out, "\"")
|
|
out = strings.ReplaceAll(out, `\u00a0`, " ")
|
|
|
|
if out != "" {
|
|
fmt.Print("\r")
|
|
fmt.Print(out)
|
|
} else {
|
|
fmt.Print("\n")
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, cmd := range commands {
|
|
cmd.Wait()
|
|
}
|
|
}
|