]> 91.132.146.200 Git - scientia.git/commitdiff
init of the add command
authorBanana <mail@bananas-playground.net>
Fri, 28 Jun 2024 22:20:22 +0000 (00:20 +0200)
committerBanana <mail@bananas-playground.net>
Fri, 28 Jun 2024 22:20:22 +0000 (00:20 +0200)
Signed-off-by: Banana <mail@bananas-playground.net>
TODO
client/go-cli/scientia/cmd/add.go [new file with mode: 0644]
client/go-cli/scientia/cmd/root.go

diff --git a/TODO b/TODO
index a40a0054935665f9d53ae931aae077737f255ab3..2771dfa9703e7f4a70bd692d903a452193803f4c 100644 (file)
--- 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 (file)
index 0000000..23a9f8f
--- /dev/null
@@ -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
+}
index 9af8f2130ff1892a46e1971fbf29f21df45936d2..11e8454240a98c614dea4899d72484ce3bdfd64e 100644 (file)
@@ -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)
+       }
+}