Translator-GO-Endpoint/main.go

196 lines
4.5 KiB
Go
Raw Normal View History

2024-03-14 21:17:46 +00:00
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
2024-06-19 08:58:32 +00:00
"sync"
2024-03-14 21:17:46 +00:00
"time"
)
type Message struct {
Message string `json:"message"`
From string `json:"from"`
To string `json:"to"`
}
const linux = "python3"
2024-03-16 09:41:43 +00:00
2024-07-29 10:12:23 +00:00
func extractMessage(message string) (string, error) {
2024-06-21 08:26:10 +00:00
var temp map[string]interface{}
2024-07-29 10:12:23 +00:00
err := json.Unmarshal([]byte(message), &temp)
2024-03-14 21:17:46 +00:00
if err != nil {
2024-07-29 10:12:23 +00:00
return "", fmt.Errorf("failed to unmarshal message: %v", err)
2024-03-14 21:17:46 +00:00
}
2024-07-29 10:12:23 +00:00
response, exists := temp["response"]
if !exists {
return "", fmt.Errorf("no 'response' field found in the message")
2024-03-14 21:17:46 +00:00
}
2024-07-29 10:12:23 +00:00
return fmt.Sprintf("%v", response), nil
2024-03-14 21:17:46 +00:00
}
func downloadPackages(w http.ResponseWriter, fromLanguage, toLanguage string) {
messages := make(chan string)
defer close(messages)
go extractMessage(w, messages)
2024-03-14 21:17:46 +00:00
cmd := exec.Command(linux, "translator/download.py", fromLanguage, toLanguage)
2024-03-14 21:17:46 +00:00
output, err := cmd.StdoutPipe()
if err != nil {
messages <- fmt.Sprintf("Error starting Download: %s", err.Error())
return
}
err = cmd.Start()
if err != nil {
messages <- fmt.Sprintf("Error starting Download: %s", err.Error())
return
}
messages <- "Download started..."
ticker := time.NewTicker(2 * time.Second)
go func() {
for range ticker.C {
messages <- ". . ."
}
}()
2024-03-14 21:17:46 +00:00
scanner := bufio.NewScanner(output)
firstOutputReceived := false
2024-03-14 21:17:46 +00:00
for scanner.Scan() {
if !firstOutputReceived {
ticker.Stop()
firstOutputReceived = true
}
messages <- scanner.Text()
2024-03-14 21:17:46 +00:00
}
err = cmd.Wait()
if err != nil {
messages <- fmt.Sprintf("Error waiting for Download: %s", err.Error())
return
}
}
func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage string) {
messages := make(chan string)
defer close(messages)
go extractMessage(w, messages)
2024-06-21 08:26:10 +00:00
cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage)
2024-03-14 21:17:46 +00:00
output, err := cmd.StdoutPipe()
if err != nil {
messages <- fmt.Sprintf("Error starting Translation: %s", err.Error())
return
}
err = cmd.Start()
if err != nil {
messages <- fmt.Sprintf("Error starting Translation: %s", err.Error())
return
}
scanner := bufio.NewScanner(output)
for scanner.Scan() {
2024-06-21 08:26:10 +00:00
// Directly send the translated text as a message
messages <- scanner.Text()
2024-03-14 21:17:46 +00:00
}
err = cmd.Wait()
if err != nil {
messages <- fmt.Sprintf("Error waiting for Translation: %s", err.Error())
return
}
}
func CheckLanguagesInstalled(fromCode, toCode string) (bool, error) {
homeDir, err := os.UserHomeDir()
2024-03-14 21:17:46 +00:00
if err != nil {
return false, fmt.Errorf("unable to determine the user home directory: %w", err)
2024-03-14 21:17:46 +00:00
}
targetDir := filepath.Join(homeDir, ".local", "share", "argos-translate", "packages", fromCode+"_"+toCode)
2024-03-14 21:17:46 +00:00
_, err = os.Stat(targetDir)
2024-03-14 21:17:46 +00:00
if err != nil {
if os.IsNotExist(err) {
2024-06-19 08:58:32 +00:00
return false, nil
}
return false, fmt.Errorf("error checking for language directory: %w", err)
2024-03-14 21:17:46 +00:00
}
return true, nil
2024-03-14 21:17:46 +00:00
}
2024-06-19 08:58:32 +00:00
2024-03-14 21:17:46 +00:00
func handleRequest(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Request content type must be application/json", http.StatusBadRequest)
return
}
2024-06-21 07:39:35 +00:00
body, err := io.ReadAll(io.NopCloser(io.Reader(r.Body)))
2024-03-14 21:17:46 +00:00
if err != nil {
http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
var msg Message
err = json.Unmarshal(body, &msg)
if err != nil {
http.Error(w, "Error unmarshalling JSON: "+err.Error(), http.StatusBadRequest)
return
}
if len(msg.From) > 2 || len(msg.To) > 2 {
http.Error(w, "From and To fields should not be longer than 2 letters.", http.StatusBadRequest)
return
2024-06-19 08:58:32 +00:00
}
installed, err := CheckLanguagesInstalled(msg.From, msg.To)
if err != nil {
if err.Error() == "file not found" {
http.Error(w, "file not found "+err.Error(), http.StatusInternalServerError)
} else {
fmt.Println("An error occurred:", err)
2024-03-14 21:17:46 +00:00
}
2024-06-19 08:58:32 +00:00
return
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
2024-03-14 21:17:46 +00:00
if installed {
executeTranslator(w, msg.Message, msg.From, msg.To)
} else {
downloadPackages(w, msg.From, msg.To)
}
2024-06-19 08:58:32 +00:00
}()
wg.Wait()
2024-03-14 21:17:46 +00:00
}
func main() {
2024-06-19 08:58:32 +00:00
http.HandleFunc("/", handleRequest)
port := "53184"
2024-05-27 09:41:28 +00:00
address := fmt.Sprintf("0.0.0.0:%s", port)
fmt.Printf("Listening on %s...\n", address)
err := http.ListenAndServe(address, nil)
if err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}