playvideo

package module
v0.0.0-...-fa7855b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 20 Imported by: 0

README

PlayVideo Go SDK

CI Go Reference Go Report Card

Official Go SDK for the PlayVideo API - Video hosting for developers.

Installation

go get github.com/PlayVideo-dev/playvideo-go

Requirements

  • Go 1.21 or later

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/PlayVideo-dev/playvideo-go"
)

func main() {
    // Create a client with your API key
    client := playvideo.NewClient("play_live_xxx")

    ctx := context.Background()

    // List collections
    collections, err := client.Collections.List(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Found %d collections\n", len(collections.Collections))

    // Upload a video
    upload, err := client.Videos.UploadFile(ctx, "./video.mp4", "my-collection", nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Uploaded video: %s\n", upload.Video.ID)
}

Configuration

// With custom options
client := playvideo.NewClient("play_live_xxx",
    playvideo.WithBaseURL("https://api.playvideo.dev/api/v1"),
    playvideo.WithTimeout(60 * time.Second),
    playvideo.WithHTTPClient(&http.Client{
        Transport: &http.Transport{
            MaxIdleConns: 10,
        },
    }),
)

Usage Examples

Collections
ctx := context.Background()

// List all collections
collections, err := client.Collections.List(ctx)

// Create a collection
collection, err := client.Collections.Create(ctx, &playvideo.CreateCollectionParams{
    Name:        "My Collection",
    Description: playvideo.String("Optional description"),
})

// Get a collection with videos
collection, err := client.Collections.Get(ctx, "my-collection")

// Delete a collection
err := client.Collections.Delete(ctx, "my-collection")
Videos
ctx := context.Background()

// List videos with filters
videos, err := client.Videos.List(ctx, &playvideo.VideoListParams{
    Collection: "my-collection",
    Status:     playvideo.VideoStatusCompleted,
    Limit:      10,
})

// Upload from file path
upload, err := client.Videos.UploadFile(ctx, "./video.mp4", "my-collection", func(p playvideo.UploadProgress) {
    fmt.Printf("Upload progress: %d%%\n", p.Percent)
})

// Upload from io.Reader
file, _ := os.Open("./video.mp4")
defer file.Close()
upload, err := client.Videos.Upload(ctx, file, "video.mp4", "my-collection", nil)

// Get a video
video, err := client.Videos.Get(ctx, "video-id")

// Delete a video
err := client.Videos.Delete(ctx, "video-id")

// Get embed info
embedInfo, err := client.Videos.GetEmbedInfo(ctx, "video-id")
Watch Processing Progress (SSE)
ctx := context.Background()

// Watch video processing progress
events, errs := client.Videos.WatchProgress(ctx, "video-id")

for {
    select {
    case event, ok := <-events:
        if !ok {
            return // Channel closed
        }
        fmt.Printf("Stage: %s, Message: %s\n", event.Stage, event.Message)
        
        if event.Stage == playvideo.ProgressStageCompleted {
            fmt.Printf("Processing complete! Playlist: %s\n", event.PlaylistURL)
        }
    case err := <-errs:
        if err != nil {
            log.Fatal(err)
        }
    }
}
Webhooks
ctx := context.Background()

// List webhooks
webhooks, err := client.Webhooks.List(ctx)

// Create a webhook
webhook, err := client.Webhooks.Create(ctx, &playvideo.CreateWebhookParams{
    URL: "https://example.com/webhook",
    Events: []playvideo.WebhookEventType{
        playvideo.WebhookEventVideoCompleted,
        playvideo.WebhookEventVideoFailed,
    },
})
fmt.Printf("Webhook secret: %s\n", webhook.Webhook.Secret)

// Update a webhook
updated, err := client.Webhooks.Update(ctx, "webhook-id", &playvideo.UpdateWebhookParams{
    IsActive: playvideo.Bool(false),
})

// Test a webhook
result, err := client.Webhooks.Test(ctx, "webhook-id")

// Delete a webhook
err := client.Webhooks.Delete(ctx, "webhook-id")
Webhook Signature Verification
import "github.com/PlayVideo-dev/playvideo-go"

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    payload, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("X-PlayVideo-Signature")
    timestamp := r.Header.Get("X-PlayVideo-Timestamp")
    secret := "whsec_xxx" // Your webhook secret

    // Verify and parse the event
    event, err := playvideo.ConstructEvent(payload, signature, timestamp, secret)
    if err != nil {
        if playvideo.IsWebhookSignatureError(err) {
            http.Error(w, "Invalid signature", http.StatusBadRequest)
            return
        }
        http.Error(w, "Error", http.StatusInternalServerError)
        return
    }

    // Handle the event
    switch event.Event {
    case playvideo.WebhookEventVideoCompleted:
        fmt.Printf("Video completed: %v\n", event.Data)
    case playvideo.WebhookEventVideoFailed:
        fmt.Printf("Video failed: %v\n", event.Data)
    }

    w.WriteHeader(http.StatusOK)
}
Embed Settings
ctx := context.Background()

// Get embed settings
settings, err := client.Embed.GetSettings(ctx)

// Update embed settings
updated, err := client.Embed.UpdateSettings(ctx, &playvideo.UpdateEmbedSettingsParams{
    PrimaryColor:   playvideo.String("#FF0000"),
    Autoplay:       playvideo.Bool(true),
    AllowLocalhost: playvideo.Bool(true),
})

// Sign an embed URL
signed, err := client.Embed.Sign(ctx, &playvideo.SignEmbedParams{
    VideoID: "video-id",
})
fmt.Printf("Embed URL: %s\n", signed.EmbedURL)
API Keys
ctx := context.Background()

// List API keys
keys, err := client.APIKeys.List(ctx)

// Create an API key
key, err := client.APIKeys.Create(ctx, &playvideo.CreateAPIKeyParams{
    Name: "My API Key",
})
fmt.Printf("New API key: %s\n", key.APIKey.Key) // Only shown once!

// Delete an API key
err := client.APIKeys.Delete(ctx, "key-id")
Account
ctx := context.Background()

// Get account info
account, err := client.Account.Get(ctx)
fmt.Printf("Plan: %s\n", account.Plan)

// Update account
updated, err := client.Account.Update(ctx, &playvideo.UpdateAccountParams{
    AllowedDomains: []string{"example.com", "*.example.com"},
    AllowLocalhost: playvideo.Bool(true),
})
Usage
ctx := context.Background()

// Get usage info
usage, err := client.Usage.Get(ctx)
fmt.Printf("Videos this month: %d\n", usage.Usage.VideosThisMonth)
fmt.Printf("Storage used: %s GB\n", usage.Usage.StorageUsedGB)

Error Handling

The SDK provides typed errors for easy handling:

video, err := client.Videos.Get(ctx, "non-existent-id")
if err != nil {
    if playvideo.IsNotFoundError(err) {
        fmt.Println("Video not found")
    } else if playvideo.IsAuthenticationError(err) {
        fmt.Println("Invalid API key")
    } else if playvideo.IsRateLimitError(err) {
        fmt.Println("Rate limited, try again later")
    } else {
        fmt.Printf("Error: %v\n", err)
    }
}

Available error types:

  • AuthenticationError - Invalid or missing API key (401)
  • AuthorizationError - Insufficient permissions (403)
  • NotFoundError - Resource not found (404)
  • ValidationError - Invalid request parameters (400/422)
  • ConflictError - Resource conflict (409)
  • RateLimitError - Too many requests (429)
  • ServerError - Server error (5xx)
  • NetworkError - Connection issues
  • TimeoutError - Request timeout
  • WebhookSignatureError - Invalid webhook signature

Helper Functions

// Create pointer to string
s := playvideo.String("value")

// Create pointer to bool  
b := playvideo.Bool(true)

// Create pointer to int
i := playvideo.Int(42)

// Create pointer to float64
f := playvideo.Float64(3.14)

MCP Server

Use the PlayVideo MCP server to connect Claude/Desktop assistants to your account.

npm install -g @playvideo/playvideo-mcp

Repo: https://github.com/PlayVideo-dev/playvideo-mcp

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.

Documentation

Overview

Package playvideo provides an official Go SDK for the PlayVideo API.

PlayVideo is a video hosting platform for developers. This SDK provides a simple interface to interact with the PlayVideo API.

Basic usage:

client := playvideo.NewClient("play_live_xxx")

// List collections
collections, err := client.Collections.List(context.Background())
if err != nil {
    log.Fatal(err)
}

// Upload a video
upload, err := client.Videos.UploadFile(context.Background(), "./video.mp4", "my-collection", nil)
if err != nil {
    log.Fatal(err)
}

// Watch processing progress
for event := range client.Videos.WatchProgress(context.Background(), upload.Video.ID) {
    fmt.Printf("%s: %s\n", event.Stage, event.Message)
}

Index

Constants

View Source
const (
	// DefaultBaseURL is the default API base URL
	DefaultBaseURL = "https://api.playvideo.dev/api/v1"
	// DefaultTimeout is the default request timeout
	DefaultTimeout = 30 * time.Second
)
View Source
const DefaultWebhookTolerance = 300

DefaultWebhookTolerance is the default maximum age of a webhook in seconds

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the given bool value

func Float64

func Float64(v float64) *float64

Float64 returns a pointer to the given float64 value

func Int

func Int(v int) *int

Int returns a pointer to the given int value

func Int64

func Int64(v int64) *int64

Int64 returns a pointer to the given int64 value

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError checks if the error is an authentication error

func IsAuthorizationError

func IsAuthorizationError(err error) bool

IsAuthorizationError checks if the error is an authorization error

func IsConflictError

func IsConflictError(err error) bool

IsConflictError checks if the error is a conflict error

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks if the error is a network error

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if the error is a not found error

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError checks if the error is a rate limit error

func IsServerError

func IsServerError(err error) bool

IsServerError checks if the error is a server error

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks if the error is a timeout error

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if the error is a validation error

func IsWebhookSignatureError

func IsWebhookSignatureError(err error) bool

IsWebhookSignatureError checks if the error is a webhook signature error

func String

func String(v string) *string

String returns a pointer to the given string value

func VerifyWebhookSignature

func VerifyWebhookSignature(payload []byte, signature, timestamp, secret string, tolerance int) error

VerifyWebhookSignature verifies a webhook signature

Parameters:

  • payload: The raw webhook payload (as bytes or string)
  • signature: The X-PlayVideo-Signature header value
  • timestamp: The X-PlayVideo-Timestamp header value
  • secret: Your webhook secret (whsec_xxx)
  • tolerance: Maximum age of the webhook in seconds (use 0 for default of 300s)

Returns nil if valid, WebhookSignatureError if invalid

Types

type APIKey

type APIKey struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	KeyPrefix  string     `json:"keyPrefix"`
	LastUsedAt *time.Time `json:"lastUsedAt"`
	ExpiresAt  *time.Time `json:"expiresAt"`
	CreatedAt  time.Time  `json:"createdAt"`
}

APIKey represents an API key

type APIKeyListResponse

type APIKeyListResponse struct {
	APIKeys []APIKey `json:"apiKeys"`
}

APIKeyListResponse is the response for listing API keys

type APIKeyWithKey

type APIKeyWithKey struct {
	APIKey
	Key string `json:"key"`
}

APIKeyWithKey is an API key with the full key value (returned on creation)

type APIKeysService

type APIKeysService struct {
	// contains filtered or unexported fields
}

APIKeysService handles API key-related operations

func (*APIKeysService) Create

Create creates a new API key

func (*APIKeysService) Delete

func (s *APIKeysService) Delete(ctx context.Context, id string) error

Delete deletes an API key by ID

func (*APIKeysService) List

List retrieves all API keys

type Account

type Account struct {
	ID             string    `json:"id"`
	Email          string    `json:"email"`
	Name           *string   `json:"name"`
	Plan           Plan      `json:"plan"`
	AllowedDomains []string  `json:"allowedDomains"`
	AllowLocalhost bool      `json:"allowLocalhost"`
	R2BucketName   *string   `json:"r2BucketName"`
	R2BucketRegion *string   `json:"r2BucketRegion"`
	CreatedAt      time.Time `json:"createdAt"`
}

Account represents a user account

type AccountService

type AccountService struct {
	// contains filtered or unexported fields
}

AccountService handles account-related API operations

func (*AccountService) Get

func (s *AccountService) Get(ctx context.Context) (*Account, error)

Get retrieves the current account information

func (*AccountService) Update

Update updates the account settings

type AuthenticationError

type AuthenticationError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

AuthenticationError represents a 401 authentication error

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type AuthorizationError

type AuthorizationError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

AuthorizationError represents a 403 authorization error

func (*AuthorizationError) Error

func (e *AuthorizationError) Error() string

type Client

type Client struct {

	// API Resources
	Collections *CollectionsService
	Videos      *VideosService
	Webhooks    *WebhooksService
	Embed       *EmbedService
	APIKeys     *APIKeysService
	Account     *AccountService
	Usage       *UsageService
	// contains filtered or unexported fields
}

Client is the PlayVideo API client

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient creates a new PlayVideo API client

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures the client

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL sets a custom base URL for the API

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the request timeout

type Collection

type Collection struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Slug        string    `json:"slug"`
	Description *string   `json:"description"`
	VideoCount  int       `json:"videoCount"`
	StorageUsed int64     `json:"storageUsed"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

Collection represents a video collection

type CollectionListResponse

type CollectionListResponse struct {
	Collections []Collection `json:"collections"`
}

CollectionListResponse is the response for listing collections

type CollectionWithVideos

type CollectionWithVideos struct {
	Collection
	Videos []Video `json:"videos"`
}

CollectionWithVideos is a collection with its videos

type CollectionsService

type CollectionsService struct {
	// contains filtered or unexported fields
}

CollectionsService handles collection-related API operations

func (*CollectionsService) Create

Create creates a new collection

func (*CollectionsService) Delete

func (s *CollectionsService) Delete(ctx context.Context, slug string) error

Delete deletes a collection by slug

func (*CollectionsService) Get

Get retrieves a collection by slug

func (*CollectionsService) List

List retrieves all collections

type ConflictError

type ConflictError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

ConflictError represents a 409 conflict error

func (*ConflictError) Error

func (e *ConflictError) Error() string

type CreateAPIKeyParams

type CreateAPIKeyParams struct {
	Name string `json:"name"`
}

CreateAPIKeyParams are the parameters for creating an API key

type CreateAPIKeyResponse

type CreateAPIKeyResponse struct {
	Message string        `json:"message"`
	APIKey  APIKeyWithKey `json:"apiKey"`
}

CreateAPIKeyResponse is the response from creating an API key

type CreateCollectionParams

type CreateCollectionParams struct {
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
}

CreateCollectionParams are the parameters for creating a collection

type CreateWebhookParams

type CreateWebhookParams struct {
	URL    string             `json:"url"`
	Events []WebhookEventType `json:"events"`
}

CreateWebhookParams are the parameters for creating a webhook

type CreateWebhookResponse

type CreateWebhookResponse struct {
	Message string            `json:"message"`
	Webhook WebhookWithSecret `json:"webhook"`
}

CreateWebhookResponse is the response from creating a webhook

type EmbedCode

type EmbedCode struct {
	Responsive string `json:"responsive"`
	Fixed      string `json:"fixed"`
}

EmbedCode contains HTML embed code snippets

type EmbedService

type EmbedService struct {
	// contains filtered or unexported fields
}

EmbedService handles embed settings API operations

func (*EmbedService) GetSettings

func (s *EmbedService) GetSettings(ctx context.Context) (*EmbedSettings, error)

GetSettings retrieves the current embed settings

func (*EmbedService) Sign

Sign generates a signed embed URL for a video

func (*EmbedService) UpdateSettings

UpdateSettings updates the embed settings

type EmbedSettings

type EmbedSettings struct {
	AllowedDomains      []string     `json:"allowedDomains"`
	AllowLocalhost      bool         `json:"allowLocalhost"`
	PrimaryColor        string       `json:"primaryColor"`
	AccentColor         string       `json:"accentColor"`
	LogoURL             *string      `json:"logoUrl"`
	LogoPosition        LogoPosition `json:"logoPosition"`
	LogoOpacity         float64      `json:"logoOpacity"`
	ShowPlaybackSpeed   bool         `json:"showPlaybackSpeed"`
	ShowQualitySelector bool         `json:"showQualitySelector"`
	ShowFullscreen      bool         `json:"showFullscreen"`
	ShowVolume          bool         `json:"showVolume"`
	ShowProgress        bool         `json:"showProgress"`
	ShowTime            bool         `json:"showTime"`
	ShowKeyboardHints   bool         `json:"showKeyboardHints"`
	Autoplay            bool         `json:"autoplay"`
	Muted               bool         `json:"muted"`
	Loop                bool         `json:"loop"`
}

EmbedSettings represents player embed settings

type Error

type Error struct {
	// HTTP status code (0 for non-HTTP errors)
	StatusCode int `json:"statusCode,omitempty"`

	// Error message
	Message string `json:"message"`

	// Error code (e.g., "authentication_error")
	Code string `json:"code,omitempty"`

	// Request ID for debugging
	RequestID string `json:"requestId,omitempty"`

	// Parameter that caused the error (for validation errors)
	Param string `json:"param,omitempty"`

	// Seconds to wait before retrying (for rate limit errors)
	RetryAfter int `json:"retryAfter,omitempty"`

	// Underlying error
	Err error `json:"-"`
}

Error represents a PlayVideo API error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error

type LogoPosition

type LogoPosition string

LogoPosition represents the position of a logo in the video player

const (
	LogoPositionTopLeft     LogoPosition = "top-left"
	LogoPositionTopRight    LogoPosition = "top-right"
	LogoPositionBottomLeft  LogoPosition = "bottom-left"
	LogoPositionBottomRight LogoPosition = "bottom-right"
)

type NetworkError

type NetworkError struct {
	Message string
	Err     error
}

NetworkError represents a network/connection error

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type NotFoundError

type NotFoundError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

NotFoundError represents a 404 not found error

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type Plan

type Plan string

Plan represents a subscription plan

const (
	PlanFree     Plan = "FREE"
	PlanPro      Plan = "PRO"
	PlanBusiness Plan = "BUSINESS"
)

type ProgressEvent

type ProgressEvent struct {
	Stage         ProgressStage `json:"stage"`
	Message       string        `json:"message,omitempty"`
	Error         string        `json:"error,omitempty"`
	PlaylistURL   string        `json:"playlistUrl,omitempty"`
	ThumbnailURL  *string       `json:"thumbnailUrl,omitempty"`
	PreviewURL    *string       `json:"previewUrl,omitempty"`
	Duration      float64       `json:"duration,omitempty"`
	ProcessedSize *int64        `json:"processedSize,omitempty"`
	Resolutions   []string      `json:"resolutions,omitempty"`
}

ProgressEvent represents a video processing progress event

type ProgressStage

type ProgressStage string

ProgressStage represents the stage in video processing progress

const (
	ProgressStagePending    ProgressStage = "pending"
	ProgressStageProcessing ProgressStage = "processing"
	ProgressStageCompleted  ProgressStage = "completed"
	ProgressStageFailed     ProgressStage = "failed"
	ProgressStageTimeout    ProgressStage = "timeout"
)

type RateLimitError

type RateLimitError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
	RetryAfter int
}

RateLimitError represents a 429 rate limit error

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type ServerError

type ServerError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

ServerError represents a 5xx server error

func (*ServerError) Error

func (e *ServerError) Error() string

type SignEmbedParams

type SignEmbedParams struct {
	VideoID string  `json:"videoId"`
	BaseURL *string `json:"baseUrl,omitempty"`
}

SignEmbedParams are the parameters for signing an embed URL

type SignEmbedResponse

type SignEmbedResponse struct {
	VideoID   string    `json:"videoId"`
	Signature string    `json:"signature"`
	EmbedURL  string    `json:"embedUrl"`
	EmbedCode EmbedCode `json:"embedCode"`
}

SignEmbedResponse is the response from signing an embed URL

type TestWebhookResponse

type TestWebhookResponse struct {
	Message    string  `json:"message"`
	StatusCode *int    `json:"statusCode,omitempty"`
	Error      *string `json:"error,omitempty"`
}

TestWebhookResponse is the response from testing a webhook

type TimeoutError

type TimeoutError struct {
	Message string
	Err     error
}

TimeoutError represents a timeout error

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

type UpdateAccountParams

type UpdateAccountParams struct {
	AllowedDomains []string `json:"allowedDomains,omitempty"`
	AllowLocalhost *bool    `json:"allowLocalhost,omitempty"`
}

UpdateAccountParams are the parameters for updating an account

type UpdateAccountResponse

type UpdateAccountResponse struct {
	Message string  `json:"message"`
	Account Account `json:"account"`
}

UpdateAccountResponse is the response from updating an account

type UpdateEmbedSettingsParams

type UpdateEmbedSettingsParams struct {
	AllowedDomains      []string      `json:"allowedDomains,omitempty"`
	AllowLocalhost      *bool         `json:"allowLocalhost,omitempty"`
	PrimaryColor        *string       `json:"primaryColor,omitempty"`
	AccentColor         *string       `json:"accentColor,omitempty"`
	LogoURL             *string       `json:"logoUrl,omitempty"`
	LogoPosition        *LogoPosition `json:"logoPosition,omitempty"`
	LogoOpacity         *float64      `json:"logoOpacity,omitempty"`
	ShowPlaybackSpeed   *bool         `json:"showPlaybackSpeed,omitempty"`
	ShowQualitySelector *bool         `json:"showQualitySelector,omitempty"`
	ShowFullscreen      *bool         `json:"showFullscreen,omitempty"`
	ShowVolume          *bool         `json:"showVolume,omitempty"`
	ShowProgress        *bool         `json:"showProgress,omitempty"`
	ShowTime            *bool         `json:"showTime,omitempty"`
	ShowKeyboardHints   *bool         `json:"showKeyboardHints,omitempty"`
	Autoplay            *bool         `json:"autoplay,omitempty"`
	Muted               *bool         `json:"muted,omitempty"`
	Loop                *bool         `json:"loop,omitempty"`
}

UpdateEmbedSettingsParams are the parameters for updating embed settings

type UpdateEmbedSettingsResponse

type UpdateEmbedSettingsResponse struct {
	Message  string        `json:"message"`
	Settings EmbedSettings `json:"settings"`
}

UpdateEmbedSettingsResponse is the response from updating embed settings

type UpdateWebhookParams

type UpdateWebhookParams struct {
	URL      *string            `json:"url,omitempty"`
	Events   []WebhookEventType `json:"events,omitempty"`
	IsActive *bool              `json:"isActive,omitempty"`
}

UpdateWebhookParams are the parameters for updating a webhook

type UploadProgress

type UploadProgress struct {
	Loaded  int64 `json:"loaded"`
	Total   int64 `json:"total"`
	Percent int   `json:"percent"`
}

UploadProgress represents upload progress

type UploadProgressFunc

type UploadProgressFunc func(progress UploadProgress)

UploadProgressFunc is a callback for upload progress

type UploadResponse

type UploadResponse struct {
	Message string      `json:"message"`
	Video   UploadVideo `json:"video"`
}

UploadResponse is the response from uploading a video

type UploadVideo

type UploadVideo struct {
	ID         string      `json:"id"`
	Filename   string      `json:"filename"`
	Status     VideoStatus `json:"status"`
	Collection string      `json:"collection"`
}

UploadVideo is the video info returned after upload

type Usage

type Usage struct {
	Plan   Plan        `json:"plan"`
	Usage  UsageInfo   `json:"usage"`
	Limits UsageLimits `json:"limits"`
}

Usage contains account usage and limits

type UsageInfo

type UsageInfo struct {
	VideosThisMonth  int         `json:"videosThisMonth"`
	VideosLimit      interface{} `json:"videosLimit"` // int or "unlimited"
	StorageUsedBytes int64       `json:"storageUsedBytes"`
	StorageUsedGB    string      `json:"storageUsedGB"`
	StorageLimitGB   int         `json:"storageLimitGB"`
}

UsageInfo contains usage information

type UsageLimits

type UsageLimits struct {
	MaxFileSizeMB      int      `json:"maxFileSizeMB"`
	MaxDurationMinutes int      `json:"maxDurationMinutes"`
	Resolutions        []string `json:"resolutions"`
	APIAccess          bool     `json:"apiAccess"`
	Webhooks           bool     `json:"webhooks"`
	DeliveryGB         int      `json:"deliveryGB"`
}

UsageLimits contains plan limits

type UsageService

type UsageService struct {
	// contains filtered or unexported fields
}

UsageService handles usage and limits API operations

func (*UsageService) Get

func (s *UsageService) Get(ctx context.Context) (*Usage, error)

Get retrieves the current usage and plan limits

type ValidationError

type ValidationError struct {
	StatusCode int
	Message    string
	Code       string
	RequestID  string
	Param      string
}

ValidationError represents a 400/422 validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Video

type Video struct {
	ID            string           `json:"id"`
	Filename      string           `json:"filename"`
	Status        VideoStatus      `json:"status"`
	Duration      *float64         `json:"duration"`
	OriginalSize  int64            `json:"originalSize"`
	ProcessedSize *int64           `json:"processedSize"`
	PlaylistURL   *string          `json:"playlistUrl"`
	ThumbnailURL  *string          `json:"thumbnailUrl"`
	PreviewURL    *string          `json:"previewUrl"`
	Resolutions   []string         `json:"resolutions"`
	ErrorMessage  *string          `json:"errorMessage"`
	Collection    *VideoCollection `json:"collection,omitempty"`
	CreatedAt     time.Time        `json:"createdAt"`
	UpdatedAt     time.Time        `json:"updatedAt"`
}

Video represents a video

type VideoCollection

type VideoCollection struct {
	Slug string `json:"slug"`
	Name string `json:"name"`
}

VideoCollection is the collection info embedded in a video

type VideoEmbedInfo

type VideoEmbedInfo struct {
	VideoID   string `json:"videoId"`
	Signature string `json:"signature"`
	EmbedPath string `json:"embedPath"`
}

VideoEmbedInfo contains embed information for a video

type VideoListParams

type VideoListParams struct {
	Collection string      `url:"collection,omitempty"`
	Status     VideoStatus `url:"status,omitempty"`
	Limit      int         `url:"limit,omitempty"`
	Offset     int         `url:"offset,omitempty"`
}

VideoListParams are the parameters for listing videos

type VideoListResponse

type VideoListResponse struct {
	Videos []Video `json:"videos"`
}

VideoListResponse is the response for listing videos

type VideoStatus

type VideoStatus string

VideoStatus represents the processing status of a video

const (
	VideoStatusPending    VideoStatus = "PENDING"
	VideoStatusProcessing VideoStatus = "PROCESSING"
	VideoStatusCompleted  VideoStatus = "COMPLETED"
	VideoStatusFailed     VideoStatus = "FAILED"
)

type VideosService

type VideosService struct {
	// contains filtered or unexported fields
}

VideosService handles video-related API operations

func (*VideosService) Delete

func (s *VideosService) Delete(ctx context.Context, id string) error

Delete deletes a video by ID

func (*VideosService) Get

func (s *VideosService) Get(ctx context.Context, id string) (*Video, error)

Get retrieves a video by ID

func (*VideosService) GetEmbedInfo

func (s *VideosService) GetEmbedInfo(ctx context.Context, id string) (*VideoEmbedInfo, error)

GetEmbedInfo retrieves embed information for a video

func (*VideosService) List

List retrieves videos with optional filters

func (*VideosService) Upload

func (s *VideosService) Upload(ctx context.Context, file io.Reader, filename, collection string, progressFn UploadProgressFunc) (*UploadResponse, error)

Upload uploads a video from an io.Reader

func (*VideosService) UploadFile

func (s *VideosService) UploadFile(ctx context.Context, filePath, collection string, progressFn UploadProgressFunc) (*UploadResponse, error)

UploadFile uploads a video from a file path

func (*VideosService) WatchProgress

func (s *VideosService) WatchProgress(ctx context.Context, id string) (<-chan *ProgressEvent, <-chan error)

WatchProgress watches video processing progress via SSE Returns a channel that receives progress events The channel is closed when processing completes, fails, or times out

type Webhook

type Webhook struct {
	ID        string             `json:"id"`
	URL       string             `json:"url"`
	Events    []WebhookEventType `json:"events"`
	IsActive  bool               `json:"isActive"`
	CreatedAt time.Time          `json:"createdAt"`
	UpdatedAt time.Time          `json:"updatedAt"`
}

Webhook represents a webhook configuration

type WebhookDelivery

type WebhookDelivery struct {
	ID           string           `json:"id"`
	Event        WebhookEventType `json:"event"`
	StatusCode   *int             `json:"statusCode"`
	Error        *string          `json:"error"`
	AttemptCount int              `json:"attemptCount"`
	DeliveredAt  *time.Time       `json:"deliveredAt"`
	CreatedAt    time.Time        `json:"createdAt"`
}

WebhookDelivery represents a webhook delivery attempt

type WebhookEventType

type WebhookEventType string

WebhookEventType represents the type of webhook event

const (
	WebhookEventVideoUploaded     WebhookEventType = "video.uploaded"
	WebhookEventVideoProcessing   WebhookEventType = "video.processing"
	WebhookEventVideoCompleted    WebhookEventType = "video.completed"
	WebhookEventVideoFailed       WebhookEventType = "video.failed"
	WebhookEventCollectionCreated WebhookEventType = "collection.created"
	WebhookEventCollectionDeleted WebhookEventType = "collection.deleted"
)

type WebhookListResponse

type WebhookListResponse struct {
	Webhooks        []Webhook          `json:"webhooks"`
	AvailableEvents []WebhookEventType `json:"availableEvents"`
}

WebhookListResponse is the response for listing webhooks

type WebhookPayload

type WebhookPayload struct {
	Event     WebhookEventType       `json:"event"`
	Timestamp int64                  `json:"timestamp"`
	Data      map[string]interface{} `json:"data"`
}

WebhookPayload is the structure of a webhook payload

func ConstructEvent

func ConstructEvent(payload []byte, signature, timestamp, secret string) (*WebhookPayload, error)

ConstructEvent verifies and parses a webhook event

Parameters:

  • payload: The raw webhook payload
  • signature: The X-PlayVideo-Signature header value
  • timestamp: The X-PlayVideo-Timestamp header value
  • secret: Your webhook secret (whsec_xxx)

Returns the parsed WebhookPayload if valid, error if invalid

type WebhookSignatureError

type WebhookSignatureError struct {
	Message string
}

WebhookSignatureError represents a webhook signature verification error

func NewWebhookSignatureError

func NewWebhookSignatureError(message string) *WebhookSignatureError

NewWebhookSignatureError creates a new webhook signature error

func (*WebhookSignatureError) Error

func (e *WebhookSignatureError) Error() string

type WebhookWithDeliveries

type WebhookWithDeliveries struct {
	Webhook
	RecentDeliveries []WebhookDelivery `json:"recentDeliveries"`
}

WebhookWithDeliveries is a webhook with recent delivery attempts

type WebhookWithSecret

type WebhookWithSecret struct {
	Webhook
	Secret string `json:"secret"`
}

WebhookWithSecret is a webhook with its secret (returned on creation)

type WebhooksService

type WebhooksService struct {
	// contains filtered or unexported fields
}

WebhooksService handles webhook-related API operations

func (*WebhooksService) Create

Create creates a new webhook

func (*WebhooksService) Delete

func (s *WebhooksService) Delete(ctx context.Context, id string) error

Delete deletes a webhook

func (*WebhooksService) Get

Get retrieves a webhook by ID with recent deliveries

func (*WebhooksService) List

List retrieves all webhooks

func (*WebhooksService) Test

Test sends a test event to a webhook

func (*WebhooksService) Update

func (s *WebhooksService) Update(ctx context.Context, id string, params *UpdateWebhookParams) (*Webhook, error)

Update updates a webhook

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL