Files
asciinema/api/api.go

97 lines
2.0 KiB
Go
Raw Normal View History

2014-08-03 19:50:39 +02:00
package api
import (
2014-11-02 19:04:19 +01:00
"bytes"
2014-11-13 18:39:29 +01:00
"errors"
2014-11-02 19:04:19 +01:00
"fmt"
2014-08-03 19:50:39 +02:00
"io"
"os"
"runtime"
2014-08-03 19:50:39 +02:00
)
2014-11-15 13:33:20 +01:00
type API interface {
UploadAsciicast(string) (string, error)
2014-08-03 19:50:39 +02:00
}
2014-11-15 13:33:20 +01:00
type AsciinemaAPI struct {
url string
token string
version string
http HTTP
2014-08-03 20:48:48 +02:00
}
2014-11-15 13:33:20 +01:00
func New(url, token, version string) *AsciinemaAPI {
return &AsciinemaAPI{
url: url,
token: token,
version: version,
2014-11-15 13:33:20 +01:00
http: &HTTPClient{},
}
2014-08-03 20:48:48 +02:00
}
func (a *AsciinemaAPI) UploadAsciicast(path string) (string, error) {
files, err := filesForUpload(path)
if err != nil {
return "", err
}
response, err := a.http.PostForm(
a.urlForUpload(),
2014-11-13 18:23:13 +01:00
a.username(),
a.token,
a.headersForUpload(),
files,
)
2014-11-02 19:04:19 +01:00
if err != nil {
2014-11-15 13:33:20 +01:00
return "", fmt.Errorf("Connection failed (%v)", err.Error())
2014-11-02 19:04:19 +01:00
}
defer response.Body.Close()
2015-03-02 20:31:51 +01:00
body := &bytes.Buffer{}
_, err = body.ReadFrom(response.Body)
if err != nil {
return "", err
}
2014-11-13 18:39:29 +01:00
if response.StatusCode != 200 && response.StatusCode != 201 {
2015-03-02 20:16:41 +01:00
switch response.StatusCode {
case 404:
2014-11-13 18:39:29 +01:00
return "", errors.New("Your client version is no longer supported. Please upgrade to the latest version.")
2015-03-02 20:16:41 +01:00
case 413:
return "", errors.New("Sorry, your asciicast is too big.")
2015-03-02 20:31:51 +01:00
case 422:
return "", fmt.Errorf("Invalid asciicast: %v", body.String())
2015-03-02 20:16:41 +01:00
case 504:
2014-11-13 18:39:29 +01:00
return "", errors.New("The server is down for maintenance. Try again in a minute.")
2015-03-02 20:16:41 +01:00
default:
return "", errors.New("HTTP status: " + response.Status)
2014-11-13 18:39:29 +01:00
}
}
2014-11-02 19:04:19 +01:00
return body.String(), nil
2014-08-03 20:48:48 +02:00
}
func (a *AsciinemaAPI) urlForUpload() string {
return a.url + "/api/asciicasts"
}
2014-11-15 13:33:20 +01:00
func (a *AsciinemaAPI) username() string {
return os.Getenv("USER")
}
func (a *AsciinemaAPI) headersForUpload() map[string]string {
return map[string]string{
"User-Agent": fmt.Sprintf("asciinema/%s %s/%s %s-%s", a.version, runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH),
}
}
func filesForUpload(path string) (map[string]io.ReadCloser, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
2014-11-02 19:04:19 +01:00
}
return map[string]io.ReadCloser{"asciicast:asciicast.json": file}, nil
2014-08-03 19:50:39 +02:00
}