go-twitch/api/ads/start_commercial.go

81 lines
2.4 KiB
Go
Raw Normal View History

2024-02-27 22:13:57 -05:00
package ads
import (
"context"
2024-02-27 22:13:57 -05:00
"encoding/json"
"fmt"
2024-02-27 22:13:57 -05:00
"io"
"net/http"
2024-02-27 22:13:57 -05:00
"net/url"
)
type StartCommercialRequest struct {
// The ID of the partner or affiliate broadcaster that wants to run the commercial. This ID must match the user ID found in the OAuth token.
BroadcasterID string `json:"broadcaster_id"`
// The length of the commercial to run, in seconds.
// Twitch tries to serve a commercial thats the requested length, but it may be shorter or longer.
// The maximum length you should request is 180 seconds.
Duration int `json:"duration"`
}
type StartCommercialResponse struct {
// An array that contains a single object with the status of your start commercial request.
Data []StartCommercialData `json:"data"`
}
type StartCommercialData struct {
// The length of the commercial you requested. If you request a commercial thats longer than 180 seconds, the API uses 180 seconds.
Length int `json:"length"`
// A message that indicates whether Twitch was able to serve an ad.
Message string `json:"message"`
// The number of seconds you must wait before running another commercial.
RetryAfter int `json:"retry_after"`
}
// Starts a commercial on the specified channel.
//
// NOTE: Only partners and affiliates may run commercials and they must be streaming live at the time.
//
// NOTE: Only the broadcaster may start a commercial; the broadcasters editors and moderators may not start commercials on behalf of the broadcaster.
//
// Requires a user access token that includes the channel:edit:commercial scope.
func (e *Ads) StartCommercial(ctx context.Context, body *StartCommercialRequest) (*StartCommercialResponse, error) {
2024-02-27 22:13:57 -05:00
endpoint := e.baseUrl.ResolveReference(&url.URL{Path: "channels/commercial"})
r, w := io.Pipe()
go func() {
if err := json.NewEncoder(w).Encode(body); err != nil {
2024-02-27 22:13:57 -05:00
w.CloseWithError(err)
} else {
w.Close()
}
}()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), r)
2024-02-27 22:13:57 -05:00
if err != nil {
return nil, err
}
res, err := e.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
2024-02-27 22:13:57 -05:00
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
if !statusOK {
return nil, fmt.Errorf("failed to start commercial (%d)", res.StatusCode)
}
2024-02-27 22:13:57 -05:00
var data StartCommercialResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
2024-02-27 22:13:57 -05:00
return nil, err
}
return &data, nil
}