+// $TheSupernovaDuo: suwako,v 1.5.5 2024/01/20 21:07:30 yakumo_izuru Exp $
+// Command line client for SimplyTranslate, a privacy friendly frontend to other translation engines
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+
+ "github.com/integrii/flaggy"
+ "gopkg.in/ini.v1"
+ "marisa.chaotic.ninja/suwako"
+)
+
+var conf struct {
+ engine string
+ instance string
+}
+
+var (
+ input string
+ source string = "auto"
+ target string
+)
+
+type Translate struct {
+ Output string `json:"translated_text"`
+}
+
+func errCheck(err error) {
+ if err != nil {
+ log.Println("Something happened :(")
+ log.Fatal(err)
+ }
+}
+
+func iniLoad(file string) error {
+ cfg, err := ini.Load(file)
+ if err != nil {
+ return err
+ }
+ conf.engine = cfg.Section("suwako").Key("engine").String()
+ conf.instance = cfg.Section("suwako").Key("instance").String()
+
+ return nil
+}
+
+func flagParse() {
+ flaggy.SetName("suwako")
+ flaggy.SetDescription("Command line client for SimplyTranslate")
+ flaggy.SetVersion(suwako.FullVersion())
+
+ flaggy.String(&source, "f", "from", "Source language")
+ flaggy.String(&target, "t", "to", "Target language")
+ flaggy.AddPositionalValue(&input, "input", 1, true, "Text to translate")
+
+ flaggy.Parse()
+}
+
+func main() {
+ // Flag parsing
+ flagParse()
+
+ // Load configuration file
+ config, err := os.UserConfigDir()
+ errCheck(err)
+ cfgfile := config + "/suwako/suwako.ini"
+ iniLoad(cfgfile)
+
+ // Verify command-line inputs
+ if len(target) == 0 {
+ log.Fatal("No target language")
+ }
+
+ // Map variable to struct
+ var translate Translate
+
+ // Encode input just in case
+ var encInput = url.PathEscape(input)
+
+ // Construct the final path to query
+ var queryURL = conf.instance + "/api/translate/" + "?engine=" + conf.engine + "&from=" + source + "&to=" + target + "&text=" + encInput
+
+ // Shoot danmaku to path
+ resp, err := http.Get(queryURL)
+ errCheck(err)
+ defer resp.Body.Close()
+
+ // Decode JSON response, discard everything else, print to standard output
+ _ = json.NewDecoder(resp.Body).Decode(&translate)
+ errCheck(err)
+ if len(translate.Output) == 0 {
+ log.Fatal("There was no output, maybe the server was down?")
+ } else {
+ fmt.Printf("%v\n", translate.Output)
+ }
+}