53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
package wordpress
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"federated.computer/wp-sync-slowtwitch/utilities"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type CreateImage struct {
|
|
Url string
|
|
}
|
|
|
|
type CreateImageResponse struct {
|
|
Id int `json:"id"`
|
|
Link string `json:"link"`
|
|
}
|
|
|
|
func (parameters *CreateImage) Execute(baseUrl, user, pass string) CreateImageResponse {
|
|
resp, err := http.Get(parameters.Url)
|
|
utilities.CheckError(err)
|
|
defer utilities.CloseBodyAndCheckError(resp.Body)
|
|
body, err := io.ReadAll(resp.Body)
|
|
utilities.CheckError(err)
|
|
request, err := http.NewRequest("POST", baseUrl+"media", bytes.NewReader(body))
|
|
utilities.CheckError(err)
|
|
filename := GetFileName(parameters.Url)
|
|
request.Header.Set("Content-Disposition", `attachment;filename="`+filename+`"`)
|
|
request.SetBasicAuth(user, pass)
|
|
rsp, err := http.DefaultClient.Do(request)
|
|
utilities.CheckError(err)
|
|
result, err := io.ReadAll(rsp.Body)
|
|
utilities.CheckError(err)
|
|
var data CreateImageResponse
|
|
err = json.Unmarshal(result, &data)
|
|
utilities.CheckError(err)
|
|
return data
|
|
}
|
|
|
|
func GetFileName(url string) string {
|
|
urlSlices := strings.Split(url, "/")
|
|
length := len(urlSlices)
|
|
var output string
|
|
for i, s := range urlSlices {
|
|
if i == length-1 {
|
|
output = s
|
|
}
|
|
}
|
|
return output
|
|
}
|