From 48eca6701bdba0a6ca38e521b72e28c54c050b7b Mon Sep 17 00:00:00 2001 From: Banana Date: Sat, 29 Jun 2024 00:20:22 +0200 Subject: [PATCH] init of the add command Signed-off-by: Banana --- TODO | 3 + client/go-cli/scientia/cmd/add.go | 118 +++++++++++++++++++++++++++++ client/go-cli/scientia/cmd/root.go | 32 +++++++- 3 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 client/go-cli/scientia/cmd/add.go diff --git a/TODO b/TODO index a40a005..2771dfa 100644 --- a/TODO +++ b/TODO @@ -1 +1,4 @@ + ignorewords ++ PHP better logging ++ PHP Better API ++ Go client improvements diff --git a/client/go-cli/scientia/cmd/add.go b/client/go-cli/scientia/cmd/add.go new file mode 100644 index 0000000..23a9f8f --- /dev/null +++ b/client/go-cli/scientia/cmd/add.go @@ -0,0 +1,118 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/spf13/cobra" + "io" + "log" + "net/http" + "os" + Helper "scientia/lib" +) + +func init() { + rootCmd.AddCommand(addCmd) +} + +var addCmd = &cobra.Command { + Use: "add file.ext", + Short: "Add a new entry and return the URL.", + Long: "Add a new entry based on a file or piped cat file | scientia add. Returns the url to the new entry.", + Run: func(cmd *cobra.Command, args []string) { + // check if there is a file or piped content + var inputString string + + if len(args) == 1 { + if FlagVerbose { + fmt.Println("Read from file argument") + } + bytes, err := os.ReadFile(args[0]) + Helper.ErrorCheck(err, "Error opening file") + inputString = string(bytes) + } else if stat, _ := os.Stdin.Stat(); (stat.Mode() & os.ModeCharDevice) == 0 { + if FlagVerbose { + fmt.Println("Read from piped stdin") + } + bytes, _ := io.ReadAll(os.Stdin) + inputString = string(bytes) + } else { + cmd.Help() + os.Exit(0) + } + + responseString := upload(inputString) + + response := Response{} + err := json.Unmarshal([]byte(responseString), &response) + Helper.ErrorCheck(err, "Can not parse return json") + + // print the result and link to the pasty + fmt.Printf("Status: %d\n", response.Status) + fmt.Printf("Message: %s\n", response.Message) + }, +} + +type PayloadJson struct { + Asl string `json:"asl"` + Data string `json:"data"` +} + +type Response struct { + Message string `json:"message"` + Status int `json:"status"` +} + +// Upload the given data +func upload(payload string) string { + if FlagVerbose { + fmt.Println("Starting to upload data") + } + if FlagDebug { + fmt.Println("DEBUG print payload:\n" + payload) + } + if len(payload) == 0 { + log.Fatal("Nothing provided to upload?") + } + + payloadStruct := PayloadJson { + Asl: ScientiaConfig.Endpoint.Secret, + Data: payload, + } + + jsonData, err := json.Marshal(payloadStruct) + Helper.ErrorCheck(err, "Can not create json payload") + + req, err := http.NewRequest(http.MethodPost, ScientiaConfig.Endpoint.Host, bytes.NewBuffer(jsonData)) + Helper.ErrorCheck(err, "Can not create http request") + // We need to set the content type from the writer, it includes necessary boundary as well + req.Header.Set("Content-Type", "application/json; charset=UTF-8") + req.Header.Set("User-Agent", "scientiaAgent/1.0") + + // Do the request + client := &http.Client{} + response, err := client.Do(req) + Helper.ErrorCheck(err, "POST request failed") + + responseBody, err := io.ReadAll(response.Body) + Helper.ErrorCheck(err, "Can not read response body") + if FlagVerbose { + fmt.Println("Request done") + } + + var returnVal = "" + if response.StatusCode != 200 { + returnVal = fmt.Sprintf(`{"Message": "Invalid response status. Use --debug for more information.", "Status": %d}`, response.StatusCode) + } else { + returnVal = string(responseBody) + } + + if FlagDebug { + fmt.Printf("DEBUG Response status code: %d\n", response.StatusCode) + fmt.Printf("DEBUG Response headers: %#v\n", response.Header) + fmt.Println("DEBUG Response body:\n", string(responseBody)) + } + + return returnVal +} diff --git a/client/go-cli/scientia/cmd/root.go b/client/go-cli/scientia/cmd/root.go index 9af8f21..11e8454 100644 --- a/client/go-cli/scientia/cmd/root.go +++ b/client/go-cli/scientia/cmd/root.go @@ -4,7 +4,10 @@ import ( "fmt" "github.com/kirsle/configdir" "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + "log" "os" + Helper "scientia/lib" ) // FlagVerbose is a global flag @@ -46,8 +49,10 @@ More information: https://www.bananas-playground.net/projekt/scientia/`, func init() { rootCmd.CompletionOptions.DisableDefaultCmd = true // add global flags - rootCmd.PersistentFlags().BoolVarP(&FlagVerbose, "verbose", "v", false, "verbose output") - rootCmd.PersistentFlags().BoolVarP(&FlagDebug, "debug", "d", false, "debug output") + rootCmd.PersistentFlags().BoolVar(&FlagVerbose, "verbose", false, "verbose output") + rootCmd.PersistentFlags().BoolVar(&FlagDebug, "debug", false, "debug output") + + cobra.OnInitialize(loadConfig) } func Execute() { @@ -56,3 +61,26 @@ func Execute() { os.Exit(1) } } + +// Read and make sure the basics are in the config +func loadConfig() { + if FlagDebug { + fmt.Println("DEBUG using config file: " + ScientiaConfigFile) + } + existingConfigFile, err := os.Open(ScientiaConfigFile) + Helper.ErrorCheck(err, "Can not open config file. Did you create one?") + defer existingConfigFile.Close() + + var decoder = yaml.NewDecoder(existingConfigFile) + err = decoder.Decode(&ScientiaConfig) + Helper.ErrorCheck(err, "Can not decode config file") + + if ScientiaConfig.Endpoint.Host == "" || ScientiaConfig.Endpoint.Secret == "" { + log.Fatal("Empty config?") + } + + if FlagDebug { + fmt.Println("DEBUG Endpoint: " + ScientiaConfig.Endpoint.Host) + fmt.Println("DEBUG Secret: " + ScientiaConfig.Endpoint.Secret) + } +} -- 2.39.5