github.com/sqlitebrowser/dio@v0.0.0-20240125125356-b587368e5c6b/cmd/licenceGet.go (about) 1 package cmd 2 3 import ( 4 "errors" 5 "fmt" 6 "io/ioutil" 7 "log" 8 "net/http" 9 "strings" 10 11 rq "github.com/parnurzeal/gorequest" 12 "github.com/spf13/cobra" 13 ) 14 15 // Downloads a licence from a DBHub.io cloud. 16 var licenceGetCmd = &cobra.Command{ 17 Use: "get [licence name]", 18 Short: "Downloads the text for a licence from a DBHub.io cloud, saving it to [licence name].txt", 19 RunE: func(cmd *cobra.Command, args []string) error { 20 return licenceGet(args) 21 }, 22 } 23 24 func init() { 25 licenceCmd.AddCommand(licenceGetCmd) 26 } 27 28 func licenceGet(args []string) error { 29 // Ensure a licence name was given 30 if len(args) == 0 { 31 return errors.New("No licence name specified") 32 } 33 34 // Check for the presence of "all" as a licence name 35 var licenceList []string 36 var allFound bool 37 for _, j := range args { 38 if strings.ToLower(j) == "all" { 39 allFound = true 40 } 41 } 42 43 // If the all keyword was given, then assemble the full licence list. Otherwise just use whatever was given 44 // on the command line 45 if allFound { 46 l, err := getLicences() 47 if err != nil { 48 return errors.New(fmt.Sprintf("Error when retrieving list of all licences: %s", err)) 49 } 50 for i := range l { 51 licenceList = append(licenceList, i) 52 } 53 } else { 54 licenceList = args 55 } 56 57 // Download the licence text 58 dlStatus := make(map[string]string) 59 for _, lic := range licenceList { 60 resp, body, errs := rq.New().TLSClientConfig(&TLSConfig).Get(cloud+"/licence/get"). 61 Query(fmt.Sprintf("licence=%s", lic)). 62 Set("User-Agent", fmt.Sprintf("Dio %s", DIO_VERSION)). 63 End() 64 if errs != nil { 65 for _, err := range errs { 66 log.Print(err.Error()) 67 } 68 dlStatus[lic] = "Error when downloading licence text" 69 continue 70 } 71 if resp.StatusCode != http.StatusOK { 72 if resp.StatusCode == http.StatusNotFound { 73 dlStatus[lic] = "Requested licence not found" 74 continue 75 } 76 dlStatus[lic] = fmt.Sprintf("Download failed with an error: HTTP status %d - '%v'", 77 resp.StatusCode, resp.Status) 78 continue 79 } 80 81 // Write the licence to disk 82 var ext string 83 if resp.Header.Get("Content-Type") == "text/html" { 84 ext = "html" 85 } else { 86 ext = "txt" 87 } 88 err := ioutil.WriteFile(fmt.Sprintf("%s.%s", lic, ext), []byte(body), 0644) 89 if err != nil { 90 dlStatus[lic] = err.Error() 91 } 92 dlStatus[lic] = fmt.Sprintf("Licence '%s.%s' downloaded", lic, ext) 93 } 94 95 // Display the status of the individual licence downloads 96 _, err := fmt.Fprintf(fOut, "Downloading licences from: %s...\n\n", cloud) 97 if err != nil { 98 return err 99 } 100 for i, j := range dlStatus { 101 _, err := fmt.Fprintf(fOut, " * %s: %s\n", i, j) 102 if err != nil { 103 return err 104 } 105 } 106 _, err = fmt.Fprintf(fOut, "\nCompleted\n") 107 return err 108 }