109 lines
2.2 KiB
Go
109 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
dsiApi = NewIceshrimpAPI("https://dis.sociat.ing/api", os.Getenv("DSI_TOKEN"), os.Getenv("DSI_FIELD_NAME"))
|
|
)
|
|
|
|
type IceshrimpAPI struct {
|
|
Client http.Client
|
|
Token string
|
|
BaseURL string
|
|
FieldName string
|
|
}
|
|
|
|
func NewIceshrimpAPI(baseURL string, token string, fieldName string) IceshrimpAPI {
|
|
return IceshrimpAPI{
|
|
Client: http.Client{Timeout: time.Second * 30},
|
|
BaseURL: baseURL,
|
|
Token: token,
|
|
FieldName: fieldName,
|
|
}
|
|
}
|
|
|
|
func (i IceshrimpAPI) UpdateFrontField(newValue string) {
|
|
// log.Println("UpdateFrontField")
|
|
|
|
headers := http.Header{}
|
|
headers.Add("authorization", fmt.Sprintf("Bearer %s", i.Token))
|
|
|
|
url, err := url.Parse(fmt.Sprintf("%s/i", i.BaseURL))
|
|
if err != nil {
|
|
log.Printf("[IceshrimpAPI] %s/i is not a valid URL\n%v\n", i.BaseURL, err)
|
|
return
|
|
}
|
|
|
|
resp, err := i.Client.Do(&http.Request{
|
|
URL: url,
|
|
Header: headers,
|
|
Method: "POST",
|
|
})
|
|
if err != nil || resp.StatusCode != 200 {
|
|
// todo: better error for non-200
|
|
log.Printf("[IceshrimpAPI] %s/i failed\n%v\n", i.BaseURL, err)
|
|
return
|
|
}
|
|
|
|
type field struct {
|
|
Name string `json:"name"`
|
|
Value string `json:"value"`
|
|
}
|
|
|
|
type profileFields struct {
|
|
Fields []field `json:"fields"`
|
|
}
|
|
|
|
var fields profileFields
|
|
err = json.NewDecoder(resp.Body).Decode(&fields)
|
|
if err != nil {
|
|
log.Println("[IceshrimpAPI] json decode failed", err)
|
|
return
|
|
}
|
|
|
|
// log.Println(fields)
|
|
|
|
for idx, field := range fields.Fields {
|
|
if field.Name == i.FieldName {
|
|
fields.Fields[idx].Value = newValue
|
|
break
|
|
}
|
|
}
|
|
|
|
url, err = url.Parse(fmt.Sprintf("%s/i/update", i.BaseURL))
|
|
if err != nil {
|
|
log.Printf("[IceshrimpAPI] %s/i/update is not a valid URL\n%v\n", i.BaseURL, err)
|
|
return
|
|
}
|
|
|
|
buf := bytes.Buffer{}
|
|
err = json.NewEncoder(&buf).Encode(fields)
|
|
if err != nil {
|
|
log.Println("[IceshrimpAPI] json encode failed", err)
|
|
return
|
|
}
|
|
|
|
// log.Println(buf.String())
|
|
|
|
_, err = i.Client.Do(&http.Request{
|
|
URL: url,
|
|
Method: "POST",
|
|
Header: headers,
|
|
Body: io.NopCloser(&buf),
|
|
})
|
|
if err != nil {
|
|
log.Println("[IceshrimpAPI] update call failed", err)
|
|
}
|
|
|
|
// json.NewDecoder(os.Stderr).Decode(resp.Body)
|
|
}
|