138 lines
2.5 KiB
Go
138 lines
2.5 KiB
Go
package reveil
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
)
|
|
|
|
type FederationServer struct {
|
|
URL string `json:"url"`
|
|
Delay uint `json:"delay"`
|
|
}
|
|
|
|
func (srv *FederationServer) WakeUp(seed int64) error {
|
|
req := map[string]interface{}{"seed": seed}
|
|
req_enc, err := json.Marshal(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
res, err := http.Post(srv.URL+"/api/federation/wakeup", "application/json", bytes.NewBuffer(req_enc))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
res.Body.Close()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (srv *FederationServer) WakeStop() error {
|
|
res, err := http.Post(srv.URL+"/api/federation/wakeok", "application/json", nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
res.Body.Close()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (srv *FederationServer) GetMusics() ([]Track, error) {
|
|
res, err := http.Get(srv.URL + "/api/tracks")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
var tracks []Track
|
|
err = json.NewDecoder(res.Body).Decode(&tracks)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return tracks, nil
|
|
}
|
|
|
|
func (srv *FederationServer) UpdateTrack(t *Track) error {
|
|
req_enc, err := json.Marshal(t)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req, err := http.NewRequest("PUT", srv.URL+"/api/tracks/"+t.Id.ToString(), bytes.NewBuffer(req_enc))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
if res.StatusCode == http.StatusOK {
|
|
var track Track
|
|
err = json.NewDecoder(res.Body).Decode(&track)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
var errmsg map[string]string
|
|
err = json.NewDecoder(res.Body).Decode(&errmsg)
|
|
if err != nil {
|
|
return err
|
|
} else {
|
|
return fmt.Errorf("%s", errmsg["errmsg"])
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (srv *FederationServer) SendTrack(track *Track) error {
|
|
// Retrieve file
|
|
fd, err := track.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer fd.Close()
|
|
|
|
var b bytes.Buffer
|
|
w := multipart.NewWriter(&b)
|
|
|
|
var fw io.Writer
|
|
// Add an image file
|
|
if fw, err = w.CreateFormFile("trackfile", fd.Name()); err != nil {
|
|
return err
|
|
}
|
|
if _, err = io.Copy(fw, fd); err != nil {
|
|
return err
|
|
}
|
|
|
|
w.Close()
|
|
|
|
//
|
|
req, err := http.NewRequest("POST", srv.URL+"/api/tracks", &b)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", w.FormDataContentType())
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if res.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("bad status: %s", res.Status)
|
|
}
|
|
|
|
return nil
|
|
}
|