Documentation
¶
Overview ¶
Package cloud is the Go client of dTelecom Cloud: participant tokens and room administration, live speech sessions, file transcription, WAV synthesis, translation, vision, moderation and node webhooks.
Use it only on a server: the client holds the project's API secret.
c, err := cloud.New(cloud.Options{}) // DTELECOM_API_KEY, DTELECOM_API_SECRET, DTELECOM_CLOUD_URL
t, err := c.CreateToken(ctx, cloud.TokenOptions{Room: "demo", Identity: "alice"})
// give t.Token and t.FallbackURLs to the client SDK
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func IsCode(err error, code string) bool
- type APIError
- type AdminToken
- type Client
- func (c *Client) AdminToken(ctx context.Context, room string) (*AdminToken, error)
- func (c *Client) CreateToken(ctx context.Context, opts TokenOptions) (*ParticipantToken, error)
- func (c *Client) ExtendToken(ctx context.Context, sessionID string, additional time.Duration) (*ExtendedToken, error)
- func (c *Client) GetSession(ctx context.Context, sessionID string) (*SessionCharge, error)
- func (c *Client) GetTranslation(ctx context.Context, requestID string) (*Translation, error)
- func (c *Client) ListSessions(ctx context.Context, room string, opts ListSessionsOptions) (*SessionCharges, error)
- func (c *Client) RoomService() *RoomService
- func (c *Client) Translate(ctx context.Context, opts TranslateOptions) (*Translation, error)
- type DataKind
- type DetectedLanguage
- type Enum
- type ExtendedSTTSession
- type ExtendedTTSSession
- type ExtendedToken
- type Grants
- type Int64
- type JobStatus
- type ListSessionsOptions
- type ModerateAudioOptions
- type ModerateVideoFrameOptions
- type Moderation
- type ModerationResult
- type ModerationService
- func (s *ModerationService) Audio(ctx context.Context, opts ModerateAudioOptions) (*Moderation, error)
- func (s *ModerationService) Get(ctx context.Context, requestID string) (*Moderation, error)
- func (s *ModerationService) Stream(ctx context.Context) (*ModerationStream, error)
- func (s *ModerationService) StreamTicket(ctx context.Context) (*ModerationStreamTicket, error)
- func (s *ModerationService) VideoFrame(ctx context.Context, opts ModerateVideoFrameOptions) (*Moderation, error)
- type ModerationStream
- type ModerationStreamTicket
- type NodeAPIError
- type Options
- type ParticipantInfo
- type ParticipantPermission
- type ParticipantToken
- type Request
- type RequestStatus
- type Room
- type RoomService
- func (s *RoomService) DeleteRoom(ctx context.Context, room string) error
- func (s *RoomService) GetParticipant(ctx context.Context, room, identity string) (*ParticipantInfo, error)
- func (s *RoomService) ListParticipants(ctx context.Context, room string) ([]ParticipantInfo, error)
- func (s *RoomService) MutePublishedTrack(ctx context.Context, room, identity, trackSID string, muted bool) (*TrackInfo, error)
- func (s *RoomService) RemoveParticipant(ctx context.Context, room, identity string) error
- func (s *RoomService) SendData(ctx context.Context, room string, data []byte, kind DataKind, ...) error
- func (s *RoomService) UpdateParticipant(ctx context.Context, room, identity string, opts UpdateParticipantOptions) (*ParticipantInfo, error)
- func (s *RoomService) UpdateRoomMetadata(ctx context.Context, room, metadata string) (*Room, error)
- func (s *RoomService) UpdateSubscriptions(ctx context.Context, room, identity string, trackSIDs []string, subscribe bool) error
- type STTService
- type STTSessionOptions
- type SendDataOptions
- type SessionCharge
- type SessionCharges
- type SpeakerSegment
- type SpeechSession
- type TTSService
- type TTSSessionOptions
- type TokenOptions
- type TrackInfo
- type TranscriptionJob
- type TranscriptionMedia
- type TranscriptionOptions
- type TranscriptionResult
- type TranscriptionSegment
- type TranscriptionsService
- func (s *TranscriptionsService) Create(ctx context.Context, opts TranscriptionOptions) (*TranscriptionJob, error)
- func (s *TranscriptionsService) Delete(ctx context.Context, jobID string) (*TranscriptionJob, error)
- func (s *TranscriptionsService) Get(ctx context.Context, jobID string) (*TranscriptionJob, error)
- type TranslateOptions
- type Translation
- type TranslationResult
- type UpdateParticipantOptions
- type VideoLayer
- type VisionOptions
- type VisionResult
- type VisionService
- type VisionSnapshot
- type WAVJob
- type WAVOptions
- type WAVResult
- type WAVService
- func (s *WAVService) Create(ctx context.Context, opts WAVOptions) (*WAVJob, error)
- func (s *WAVService) Delete(ctx context.Context, jobID string) (*WAVJob, error)
- func (s *WAVService) Download(ctx context.Context, jobID string) (io.ReadCloser, error)
- func (s *WAVService) Get(ctx context.Context, jobID string) (*WAVJob, error)
- type WebhookEvent
- type WebhookOptions
- type WebhookReceiver
Constants ¶
const ( EventParticipantJoined = "participant_joined" EventParticipantLeft = "participant_left" EventTrackPublished = "track_published" EventTrackUnpublished = "track_unpublished" )
Webhook event names delivered to the URLs in a participant token.
Variables ¶
var ( // ErrModerationClosed means the moderation WebSocket is closed; open a new stream. ErrModerationClosed = errors.New("dtelecom cloud: moderation connection closed") // ErrModerationBusy means a result is still pending: the stream takes one item at a time. ErrModerationBusy = errors.New("dtelecom cloud: await the previous moderation result before sending") )
var ErrRoomNotLive = errors.New("dtelecom cloud: room has no joined participants")
ErrRoomNotLive means the room has no joined participant, so there is no node to call.
Functions ¶
Types ¶
type APIError ¶
type APIError struct {
// Status is the HTTP status.
Status int
// Code is the cloud's error code, such as insufficient_balance; http_<status> when the body
// has none.
Code string
// RetryAfter is how long to wait before retrying, when the cloud says so (429s and 503s).
RetryAfter time.Duration
// ID is the job or request the error belongs to, when the cloud names one.
ID string
// Detail is what the speech or AI backend said about the input, with backend_rejected (422).
// For SSML: code, message and position, e.g.
// {"code": "UNSUPPORTED_TAG", "message": "Unsupported element: emphasis", "position": 13}.
Detail map[string]any
}
APIError is a non-2xx answer from the cloud.
type AdminToken ¶
type AdminToken struct {
Token string
// APIURLs are the HTTPS origins of the nodes hosting the room's joined participants.
// Empty when nobody has joined.
APIURLs []string
ExpiresAt time.Time
}
AdminToken authorises room administration on the nodes for 10 minutes.
type Client ¶
type Client struct {
// STT opens live speech-to-text sessions.
STT *STTService
// TTS opens live text-to-speech sessions.
TTS *TTSService
// Transcriptions transcribes audio and video files.
Transcriptions *TranscriptionsService
// WAV synthesises text or SSML into WAV files.
WAV *WAVService
// Vision answers questions about images.
Vision *VisionService
// Moderation checks audio and video frames, per item or over a WebSocket.
Moderation *ModerationService
// contains filtered or unexported fields
}
Client calls the dTelecom Cloud hosted API. It is safe for concurrent use.
func (*Client) AdminToken ¶
AdminToken mints a 10-minute room admin token and lists the nodes hosting the room. RoomService uses it; call it yourself only to reach the nodes' API directly.
func (*Client) CreateToken ¶
func (c *Client) CreateToken(ctx context.Context, opts TokenOptions) (*ParticipantToken, error)
CreateToken creates a participant session and returns its token and node URL. Every issued token counts toward the plan's concurrent participants from the moment it is issued.
func (*Client) ExtendToken ¶
func (c *Client) ExtendToken(ctx context.Context, sessionID string, additional time.Duration) (*ExtendedToken, error)
ExtendToken adds time to a session and returns a token for the whole remaining time. The current connection stays up; the client uses the new token when it connects again. It keeps the name, metadata, grants and webhook URLs.
Call it before the token expires: a participant whose token expired without an extension is removed about a minute later, and later calls fail with code session_not_extendable (409). additional is rounded up to whole minutes, at most 24 hours per call.
func (*Client) GetSession ¶ added in v1.2.0
GetSession reads a session of the project (a participant from CreateToken, or a service session) and what it was charged. Sessions are charged when they end: check Final.
func (*Client) GetTranslation ¶
GetTranslation polls a translation, or reads its stored result without another charge.
func (*Client) ListSessions ¶ added in v1.2.0
func (c *Client) ListSessions(ctx context.Context, room string, opts ListSessionsOptions) (*SessionCharges, error)
ListSessions lists a room's participant sessions and the service sessions linked to them, newest first, with their charges and the total.
func (*Client) RoomService ¶
func (c *Client) RoomService() *RoomService
RoomService administers rooms on the nodes, authorised through AdminToken. Keep the returned value to reuse its cached admin tokens.
func (*Client) Translate ¶
func (c *Client) Translate(ctx context.Context, opts TranslateOptions) (*Translation, error)
Translate translates text. Running means call again with the same key, or poll with GetTranslation. A failed translation is returned as an *APIError, such as inference_rejected (422).
type DetectedLanguage ¶
type DetectedLanguage struct {
Language string `json:"language"`
Confidence float64 `json:"confidence"`
}
DetectedLanguage is the language the model detected.
type Enum ¶
type Enum string
Enum is a protobuf enum value by name, such as AUDIO. Numbers sent by older nodes are kept as their decimal text.
func (*Enum) UnmarshalJSON ¶
type ExtendedSTTSession ¶
ExtendedSTTSession carries the new key; send it to the open socket as {"type": "extend", "session_key": token}.
type ExtendedTTSSession ¶
type ExtendedTTSSession struct {
Token string
// MaxCharacters the session may now synthesise in total.
MaxCharacters int
ExpiresAt time.Time
}
ExtendedTTSSession carries the new key; send it to the open socket as {"type": "extend", "session_key": token}.
type ExtendedToken ¶
type ExtendedToken struct {
Token string
WsURL string
// FallbackURLs contains WsURL first, followed by distinct alternatives in Cloud preference order.
FallbackURLs []string
// Region is the session's node location, as in CreateToken.
Region string
ExpiresAt time.Time
}
ExtendedToken is a token for the whole remaining time of an extended session.
type Grants ¶
Grants narrow a participant's node permissions. Nil fields keep their defaults: publish, subscribe and data are allowed, room admin is not.
type Int64 ¶
type Int64 int64
Int64 is an int64 that decodes from a JSON number or a string, as protobuf JSON writes int64.
func (*Int64) UnmarshalJSON ¶
type JobStatus ¶
type JobStatus string
JobStatus is the state of a file job: uploading, queued, running, completed, failed, cancelled or deleted.
type ListSessionsOptions ¶ added in v1.2.0
type ListSessionsOptions struct {
// Since drops sessions created before it; a room name can be reused.
Since time.Time
// Limit caps the result: default 100, at most 500.
Limit int
}
ListSessionsOptions narrows ListSessions.
type ModerateAudioOptions ¶
type ModerateAudioOptions struct {
// Audio is mono PCM16 little-endian at 16 kHz, up to 30 seconds.
Audio []byte
// IdempotencyKey is 1-128 letters, digits, underscores or hyphens.
IdempotencyKey string
Language string
// WebRTCSessionID links the request to a room participant.
WebRTCSessionID string
}
ModerateAudioOptions moderate an audio chunk.
type ModerateVideoFrameOptions ¶
type ModerateVideoFrameOptions struct {
// Image up to 6 MiB.
Image []byte
// IdempotencyKey is 1-128 letters, digits, underscores or hyphens.
IdempotencyKey string
// WebRTCSessionID links the request to a room participant.
WebRTCSessionID string
}
ModerateVideoFrameOptions moderate one video frame.
type Moderation ¶
type Moderation = Request[ModerationResult]
Moderation is a moderation request; Kind is moderation-audio or moderation-video.
type ModerationResult ¶
type ModerationResult struct {
// Policy is text_safety (audio) or visual_safety (video).
Policy string `json:"policy"`
PolicyVersion string `json:"policy_version"`
// EvaluatedCategories are the categories the combined policy covers, not one prediction
// per category.
EvaluatedCategories []string `json:"evaluated_categories"`
// Decision is pass or flag.
Decision string `json:"decision"`
Evidence struct {
Model string `json:"model"`
YesProbability float64 `json:"yes_probability"`
Calibrated bool `json:"calibrated"`
ScoreType string `json:"score_type"`
} `json:"evidence"`
ImageScreening *struct {
Model string `json:"model"`
NativeScores map[string]float64 `json:"native_scores"`
Calibrated bool `json:"calibrated"`
} `json:"image_screening,omitempty"`
// Transcript and Language are set for audio.
Transcript string `json:"transcript,omitempty"`
Language string `json:"language,omitempty"`
Usage struct {
CompletedFrames int `json:"completed_frames,omitempty"`
AudioSamples int64 `json:"audio_samples,omitempty"`
SampleRate int `json:"sample_rate,omitempty"`
} `json:"usage"`
}
ModerationResult is a moderation decision.
type ModerationService ¶
type ModerationService struct {
// contains filtered or unexported fields
}
ModerationService checks audio and video frames, per item or over a WebSocket.
func (*ModerationService) Audio ¶
func (s *ModerationService) Audio(ctx context.Context, opts ModerateAudioOptions) (*Moderation, error)
Audio moderates an audio chunk.
func (*ModerationService) Get ¶
func (s *ModerationService) Get(ctx context.Context, requestID string) (*Moderation, error)
Get polls a request, or reads its stored result without another charge.
func (*ModerationService) Stream ¶
func (s *ModerationService) Stream(ctx context.Context) (*ModerationStream, error)
Stream gets a ticket and opens the moderation WebSocket with it.
func (*ModerationService) StreamTicket ¶
func (s *ModerationService) StreamTicket(ctx context.Context) (*ModerationStreamTicket, error)
StreamTicket returns a ticket for one moderation WebSocket, valid for 10 minutes; Stream gets one and connects. Moderation runs on your backend, which acts on the results.
func (*ModerationService) VideoFrame ¶
func (s *ModerationService) VideoFrame(ctx context.Context, opts ModerateVideoFrameOptions) (*Moderation, error)
VideoFrame moderates one video frame.
type ModerationStream ¶
type ModerationStream struct {
// contains filtered or unexported fields
}
ModerationStream is a moderation WebSocket: send audio chunks or video frames one at a time and get each result. Each item is billed like the HTTP call. There is no capture, sampling or retry. Methods are safe for concurrent use, but only one item is in flight at a time.
func ConnectModerationStream ¶
func ConnectModerationStream(ctx context.Context, ticket *ModerationStreamTicket) (*ModerationStream, error)
ConnectModerationStream opens a stream with a ticket from Moderation.StreamTicket.
func (*ModerationStream) SendAudio ¶
func (s *ModerationStream) SendAudio(ctx context.Context, idempotencyKey string, pcm []byte, language string) (*Moderation, error)
SendAudio moderates mono PCM16 little-endian audio at 16 kHz, up to 30 seconds. language defaults to en.
func (*ModerationStream) SendVideoFrame ¶
func (s *ModerationStream) SendVideoFrame(ctx context.Context, idempotencyKey string, image []byte) (*Moderation, error)
SendVideoFrame moderates one image, up to 6 MiB.
type ModerationStreamTicket ¶
type ModerationStreamTicket struct {
Token string
// WebSocketURL is the wss:// URL of the stream.
WebSocketURL string
ExpiresAt time.Time
Protocol string
MaxInflight int
AudioFormat string
SampleRate int
Channels int
MaxAudioSeconds int
}
ModerationStreamTicket opens one moderation WebSocket from your backend with ConnectModerationStream.
type NodeAPIError ¶
type NodeAPIError struct {
// APIURL is the node that answered.
APIURL string
// Status is the HTTP status; 0 when the node was not reached.
Status int
// Code is the Twirp error code, such as not_found.
Code string
Message string
}
NodeAPIError is a node refusing or failing a room API call.
func (*NodeAPIError) Error ¶
func (e *NodeAPIError) Error() string
type Options ¶
type Options struct {
// APIKey of the project. Env: DTELECOM_API_KEY.
APIKey string
// APISecret of the key. Env: DTELECOM_API_SECRET.
APISecret string
// BaseURL is the cloud origin, such as https://cloud.dtelecom.org. Env: DTELECOM_CLOUD_URL.
BaseURL string
// HTTPClient sends the requests; http.DefaultClient when nil.
HTTPClient *http.Client
}
Options configure a Client. Empty fields fall back to environment variables.
type ParticipantInfo ¶
type ParticipantInfo struct {
SID string `json:"sid"`
Identity string `json:"identity"`
// State is JOINING, JOINED, ACTIVE or DISCONNECTED.
State Enum `json:"state"`
Tracks []TrackInfo `json:"tracks,omitempty"`
Metadata string `json:"metadata"`
// JoinedAt is a Unix time in seconds.
JoinedAt Int64 `json:"joinedAt"`
Name string `json:"name"`
Version uint32 `json:"version"`
Permission *ParticipantPermission `json:"permission,omitempty"`
Region string `json:"region"`
IsPublisher bool `json:"isPublisher"`
Relayed bool `json:"relayed"`
// RTTMs is the round trip time to the node, set on participant_left; 0 when not measured.
RTTMs uint32 `json:"rttMs"`
}
ParticipantInfo describes a participant.
type ParticipantPermission ¶
type ParticipantPermission struct {
CanSubscribe bool `json:"canSubscribe"`
CanPublish bool `json:"canPublish"`
CanPublishData bool `json:"canPublishData"`
CanPublishSources []string `json:"canPublishSources,omitempty"`
Hidden bool `json:"hidden"`
Recorder bool `json:"recorder"`
CanUpdateMetadata bool `json:"canUpdateMetadata"`
}
ParticipantPermission are a participant's node permissions.
type ParticipantToken ¶
type ParticipantToken struct {
Token string
// WsURL is the node URL (wss://...) for the client SDK.
WsURL string
// FallbackURLs contains WsURL first, followed by distinct alternatives in Cloud preference order.
FallbackURLs []string
// SessionID identifies the session for ExtendToken, GetSession and for linking AI usage to it.
SessionID string
// Region is where the chosen node is: its city, else its country; empty when unknown.
Region string
ExpiresAt time.Time
}
ParticipantToken is a token for the client SDK and the node to connect to.
type Request ¶
type Request[R any] struct { ID string `json:"id"` Kind string `json:"kind"` Status RequestStatus `json:"status"` // ChargedMicrocredits is the charge as a decimal string. ChargedMicrocredits string `json:"charged_microcredits"` Result *R `json:"result,omitempty"` Error string `json:"error,omitempty"` }
Request is a translation, vision or moderation request. Running means call again with the same idempotency key, or poll with the service's Get.
type RequestStatus ¶
type RequestStatus string
RequestStatus is running, completed or failed. A failed request is returned by the SDK as an *APIError, so a returned request is running or completed.
const ( RequestRunning RequestStatus = "running" RequestCompleted RequestStatus = "completed" RequestFailed RequestStatus = "failed" )
type Room ¶
type Room struct {
SID string `json:"sid"`
Name string `json:"name"`
EmptyTimeout uint32 `json:"emptyTimeout"`
MaxParticipants uint32 `json:"maxParticipants"`
// CreationTime is a Unix time in seconds.
CreationTime Int64 `json:"creationTime"`
Metadata string `json:"metadata"`
NumParticipants uint32 `json:"numParticipants"`
ActiveRecording bool `json:"activeRecording"`
// TurnPassword is a single-use TURN password for the participant the event is about.
TurnPassword string `json:"turnPassword,omitempty"`
// Key is the project's room key, on participant and track events from cloud tokens.
Key string `json:"key,omitempty"`
}
Room is a room as the nodes describe it.
type RoomService ¶
type RoomService struct {
// contains filtered or unexported fields
}
RoomService administers rooms through the nodes' Twirp API, authorised with admin tokens from the cloud. The admin token lists the nodes hosting the room's participants. A node answers reads from its own participants only, and applies a change to a participant only when it hosts that participant, so calls about a participant go to its node, room-wide calls to one hosting node, and ListParticipants to all of them. It is safe for concurrent use.
func (*RoomService) DeleteRoom ¶
func (s *RoomService) DeleteRoom(ctx context.Context, room string) error
DeleteRoom ends the room. A room nobody joined is already gone.
func (*RoomService) GetParticipant ¶
func (s *RoomService) GetParticipant(ctx context.Context, room, identity string) (*ParticipantInfo, error)
GetParticipant reads one participant.
func (*RoomService) ListParticipants ¶
func (s *RoomService) ListParticipants(ctx context.Context, room string) ([]ParticipantInfo, error)
ListParticipants lists the joined participants across the room's nodes.
func (*RoomService) MutePublishedTrack ¶
func (s *RoomService) MutePublishedTrack(ctx context.Context, room, identity, trackSID string, muted bool) (*TrackInfo, error)
MutePublishedTrack mutes or unmutes a participant's track and returns the track.
func (*RoomService) RemoveParticipant ¶
func (s *RoomService) RemoveParticipant(ctx context.Context, room, identity string) error
RemoveParticipant disconnects a participant. They can join again with a valid token.
func (*RoomService) SendData ¶
func (s *RoomService) SendData(ctx context.Context, room string, data []byte, kind DataKind, opts SendDataOptions) error
SendData sends a data message to the room, or to opts.DestinationSIDs only. The node that takes it delivers it to its participants and relays it to the room's other nodes, so it goes to one hosting node.
func (*RoomService) UpdateParticipant ¶
func (s *RoomService) UpdateParticipant(ctx context.Context, room, identity string, opts UpdateParticipantOptions) (*ParticipantInfo, error)
UpdateParticipant changes a participant's metadata, name or permissions and returns the participant. Nodes released before 2026-11-17 answer with an empty ParticipantInfo, although the change is applied.
func (*RoomService) UpdateRoomMetadata ¶
UpdateRoomMetadata sets the room's metadata and returns the room. Participants get the metadata through their room metadata callback. Nodes released before 2026-11-17 answer with an empty Room, although the metadata is set.
func (*RoomService) UpdateSubscriptions ¶
func (s *RoomService) UpdateSubscriptions(ctx context.Context, room, identity string, trackSIDs []string, subscribe bool) error
UpdateSubscriptions subscribes a participant to tracks, or unsubscribes it. Tracks are sent grouped by their publisher, which every node release accepts.
type STTService ¶
type STTService struct {
// contains filtered or unexported fields
}
STTService opens live speech-to-text sessions, prepaid by time.
func (*STTService) CreateSession ¶
func (s *STTService) CreateSession(ctx context.Context, opts STTSessionOptions) (*SpeechSession, error)
CreateSession opens a session: connect to StreamURL and send Token as session_key. A key serves one connection; after a disconnect, open a new session.
func (*STTService) Extend ¶
func (s *STTService) Extend(ctx context.Context, sessionID string, additional time.Duration) (*ExtendedSTTSession, error)
Extend adds time, rounded up to whole minutes. Send the new token to the open socket as {"type": "extend", "session_key": token}. After the session ended it fails with session_not_extendable (409).
type STTSessionOptions ¶
type STTSessionOptions struct {
// Duration is prepaid streaming time, rounded up to whole minutes, at most 24 hours.
// Unused time is released when the session ends.
Duration time.Duration
// Language code, such as en.
Language string
// WebRTCSessionID links the session to a room participant (SessionID from CreateToken).
WebRTCSessionID string
}
STTSessionOptions open a live speech-to-text session.
type SendDataOptions ¶
type SendDataOptions struct {
// DestinationSIDs are the participants to receive it; everyone when empty.
DestinationSIDs []string
Topic string
}
SendDataOptions narrow a data message.
type SessionCharge ¶ added in v1.2.0
type SessionCharge struct {
SessionID string `json:"session_id"`
// Service is "webrtc" for a participant, else the service: "stt", "tts", "file-stt", "vision", ...
Service string `json:"service"`
// Status is pending, active, completed, expired, failed or rejected.
Status string `json:"status"`
// RoomName and Identity are the participant's; for a service session, those of its linked participant.
RoomName string `json:"room_name,omitempty"`
Identity string `json:"identity,omitempty"`
// WebRTCSessionID is the participant session a service session was linked to.
WebRTCSessionID string `json:"webrtc_session_id,omitempty"`
// Region is the node location of a participant session.
Region string `json:"region,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
EndedAt *time.Time `json:"ended_at,omitempty"`
// Characters are the TTS characters used.
Characters int64 `json:"characters,omitempty"`
// ChargedMicrocredits is the charge (1,000,000 per dollar) as a decimal string; ChargedUSD the same in dollars.
ChargedMicrocredits string `json:"charged_microcredits"`
ChargedUSD string `json:"charged_usd"`
// Final is true once the session ended or was rejected; until then the charge is 0.
Final bool `json:"final"`
// CoveredByAddon is true when the bandwidth add-on covered this participant session.
CoveredByAddon bool `json:"covered_by_addon"`
}
SessionCharge is a session of the project and what it was charged.
type SessionCharges ¶ added in v1.2.0
type SessionCharges struct {
Sessions []SessionCharge `json:"sessions"`
TotalMicrocredits string `json:"total_microcredits"`
TotalUSD string `json:"total_usd"`
}
SessionCharges is a room's sessions, newest first, and their total.
type SpeakerSegment ¶
type SpeakerSegment struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Speaker string `json:"speaker"`
}
SpeakerSegment is a span spoken by one speaker.
type SpeechSession ¶
type SpeechSession struct {
SessionID string
// Token is the session key for the speech server (session_key in its protocol).
Token string
// ServerURL is the speech server origin, as signed into the key.
ServerURL string
// StreamURL is the WebSocket address to open: ServerURL + /v1/stream.
StreamURL string
ExpiresAt time.Time
}
SpeechSession is a prepaid session on a speech server. Its key serves one WebSocket connection: after any disconnect, open a new session.
type TTSService ¶
type TTSService struct {
// contains filtered or unexported fields
}
TTSService opens live text-to-speech sessions, prepaid by characters.
func (*TTSService) CreateSession ¶
func (s *TTSService) CreateSession(ctx context.Context, opts TTSSessionOptions) (*SpeechSession, error)
CreateSession opens a session: connect to StreamURL and send Token as session_key. A key serves one connection; after a disconnect, open a new session. A session lives 30 minutes.
func (*TTSService) Extend ¶
func (s *TTSService) Extend(ctx context.Context, sessionID string, additionalCharacters int) (*ExtendedTTSSession, error)
Extend adds characters and another 30 minutes. Send the new token to the open socket as {"type": "extend", "session_key": token}.
type TTSSessionOptions ¶
type TTSSessionOptions struct {
// MaxCharacters the session may synthesise. Extend with TTS.Extend.
MaxCharacters int
// Language code, such as en.
Language string
// Voice is recorded for the dashboard; the voice you hear is set in the stream's first
// message.
Voice string
// WebRTCSessionID links the session to a room participant (SessionID from CreateToken).
WebRTCSessionID string
}
TTSSessionOptions open a live text-to-speech session.
type TokenOptions ¶
type TokenOptions struct {
// Room name. A room is created when its first participant joins.
Room string
// Identity is unique within the room; a second connection with it replaces the first.
Identity string
// Name is the display name.
Name string
// Metadata is opaque data other participants can read, up to 16 KiB.
Metadata string
// TTL is the token lifetime: 6 hours when zero, at most 24 hours, rounded up to whole
// minutes. Extend the token before it expires, or the participant is removed.
TTL time.Duration
// ClientIP is the participant's public IP, used to pick the nearest node. Without it the
// node is picked near the caller, that is your server.
ClientIP string
// WebhookURLs receive this participant's room events: HTTPS only, up to 5.
WebhookURLs []string
// Grants override the default permissions.
Grants *Grants
}
TokenOptions describe a participant token.
type TrackInfo ¶
type TrackInfo struct {
SID string `json:"sid"`
// Type is AUDIO, VIDEO or DATA.
Type Enum `json:"type"`
Name string `json:"name"`
Muted bool `json:"muted"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
Simulcast bool `json:"simulcast"`
// Source is CAMERA, MICROPHONE, SCREEN_SHARE, SCREEN_SHARE_AUDIO or UNKNOWN.
Source Enum `json:"source"`
Layers []VideoLayer `json:"layers,omitempty"`
MimeType string `json:"mimeType"`
Mid string `json:"mid"`
Stereo bool `json:"stereo"`
}
TrackInfo describes a published track.
type TranscriptionJob ¶
type TranscriptionJob struct {
ID string `json:"id"`
Status JobStatus `json:"status"`
// DurationSeconds is the media length, once decoded.
DurationSeconds *float64 `json:"duration_seconds,omitempty"`
Result *TranscriptionResult `json:"result,omitempty"`
// Error is the failure code when Status is failed.
Error string `json:"error,omitempty"`
}
TranscriptionJob is a file transcription.
type TranscriptionMedia ¶
type TranscriptionMedia struct {
SampleCount int64 `json:"sample_count"`
SampleRate int `json:"sample_rate"`
Channels int `json:"channels"`
DurationSeconds float64 `json:"duration_seconds"`
}
TranscriptionMedia describes the decoded media.
type TranscriptionOptions ¶
type TranscriptionOptions struct {
// File is audio or video, up to 2 hours and 256 MiB. It is streamed, not buffered.
File io.Reader
// Filename is sent with the upload; audio.media when empty.
Filename string
// IdempotencyKey is 1-128 printable ASCII characters and is bound to this file: reuse it to
// retry the same upload; with another file it fails with idempotency_conflict (409).
IdempotencyKey string
// Language code, en when empty. auto is not accepted for files.
Language string
// Diarize labels speakers; on when nil.
Diarize *bool
}
TranscriptionOptions start a file transcription.
type TranscriptionResult ¶
type TranscriptionResult struct {
Text string `json:"text"`
Language string `json:"language"`
Segments []TranscriptionSegment `json:"segments"`
Media TranscriptionMedia `json:"media"`
// SpeakerSegments label who speaks when (speaker_1, speaker_2, ...), with diarization.
SpeakerSegments []SpeakerSegment `json:"speaker_segments,omitempty"`
// SpeakerLabels explains the labels: anonymous and file-local; overlapping voices are not
// separated.
SpeakerLabels string `json:"speaker_labels,omitempty"`
TimingType string `json:"timing_type"`
}
TranscriptionResult is a finished transcript.
type TranscriptionSegment ¶
type TranscriptionSegment struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Speaker *string `json:"speaker"`
Text string `json:"text"`
}
TranscriptionSegment is a timed piece of the transcript.
type TranscriptionsService ¶
type TranscriptionsService struct {
// contains filtered or unexported fields
}
TranscriptionsService transcribes audio and video files asynchronously.
func (*TranscriptionsService) Create ¶
func (s *TranscriptionsService) Create(ctx context.Context, opts TranscriptionOptions) (*TranscriptionJob, error)
Create uploads a file and starts a job; poll it with Get. A failed upload is not retried: call Create again with the same key.
func (*TranscriptionsService) Delete ¶
func (s *TranscriptionsService) Delete(ctx context.Context, jobID string) (*TranscriptionJob, error)
Delete cancels unfinished work, or deletes a finished result. A finished job keeps its charge.
func (*TranscriptionsService) Get ¶
func (s *TranscriptionsService) Get(ctx context.Context, jobID string) (*TranscriptionJob, error)
Get reads a job.
type TranslateOptions ¶
type TranslateOptions struct {
// Q is the text, billed per Unicode code point, up to 500.
Q string
// Target language code.
Target string
// Source language code; detected when empty.
Source string
// IdempotencyKey is 1-128 letters, digits, underscores or hyphens.
IdempotencyKey string
}
TranslateOptions describe a translation.
type Translation ¶
type Translation = Request[TranslationResult]
Translation is a translation request.
type TranslationResult ¶
type TranslationResult struct {
TranslatedText string `json:"translated_text"`
// Source is the requested source, auto when it was detected.
Source string `json:"source"`
Target string `json:"target"`
DetectedLanguage *DetectedLanguage `json:"detected_language,omitempty"`
Usage struct {
// Characters are billed; OutputTokens is informational.
Characters int `json:"characters"`
OutputTokens int `json:"output_tokens,omitempty"`
} `json:"usage"`
}
TranslationResult is a finished translation.
type UpdateParticipantOptions ¶
type UpdateParticipantOptions struct {
Metadata string
Name string
Permission *ParticipantPermission
}
UpdateParticipantOptions change a participant. Empty fields are left as they are.
type VideoLayer ¶
type VideoLayer struct {
// Quality is LOW, MEDIUM, HIGH or OFF.
Quality Enum `json:"quality"`
Width uint32 `json:"width"`
Height uint32 `json:"height"`
Bitrate uint32 `json:"bitrate"`
SSRC uint32 `json:"ssrc"`
}
VideoLayer is one simulcast layer of a video track.
type VisionOptions ¶
type VisionOptions struct {
// Image up to 6 MiB.
Image []byte
// IdempotencyKey is 1-128 letters, digits, underscores or hyphens.
IdempotencyKey string
Question string
// Source is camera or screen; camera when empty.
Source string
// WebRTCSessionID links the request to a room participant.
WebRTCSessionID string
}
VisionOptions ask a question about an image.
type VisionResult ¶
type VisionResult struct {
RequestID string `json:"request_id"`
Answer string `json:"answer"`
Model string `json:"model"`
GeneratedTokens int `json:"generated_tokens"`
PromptTokens int `json:"prompt_tokens"`
FinishReason string `json:"finish_reason"`
OutputTokenLimitReached bool `json:"output_token_limit_reached"`
Usage struct {
CompletedSnapshots int `json:"completed_snapshots"`
} `json:"usage"`
}
VisionResult is an answer about an image.
type VisionService ¶
type VisionService struct {
// contains filtered or unexported fields
}
VisionService answers questions about images with dTelecom's own vision model.
func (*VisionService) Get ¶
func (s *VisionService) Get(ctx context.Context, requestID string) (*VisionSnapshot, error)
Get polls a request, or reads its stored answer without another charge.
func (*VisionService) Snapshot ¶
func (s *VisionService) Snapshot(ctx context.Context, opts VisionOptions) (*VisionSnapshot, error)
Snapshot answers a question about an image. Running means call again with the same key, or poll with Get.
type VisionSnapshot ¶
type VisionSnapshot = Request[VisionResult]
VisionSnapshot is a vision request.
type WAVJob ¶
type WAVJob struct {
ID string `json:"id"`
Status JobStatus `json:"status"`
Characters *int `json:"characters,omitempty"`
Result *WAVResult `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
WAVJob is a WAV synthesis.
type WAVOptions ¶
type WAVOptions struct {
// Text or SSML, up to 10,000 characters.
Text string
// IdempotencyKey is 1-128 printable ASCII characters. Reusing it with different text fails
// with idempotency_conflict (409).
IdempotencyKey string
Voice string
Language string
// Speed when non-zero.
Speed float64
// InputFormat is text or ssml; text when empty.
InputFormat string
// Dictionary maps a locale to source text and its spoken alias. SSML only.
Dictionary map[string]map[string]string
// Watermark adds an audio watermark; off when nil.
Watermark *bool
}
WAVOptions start a WAV synthesis.
type WAVResult ¶
type WAVResult struct {
Characters int `json:"characters"`
SampleRate int `json:"sample_rate"`
Channels int `json:"channels"`
Encoding string `json:"encoding"`
Samples int64 `json:"samples"`
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
Watermark bool `json:"watermark"`
}
WAVResult describes a finished 48 kHz mono PCM16 WAV file.
type WAVService ¶
type WAVService struct {
// contains filtered or unexported fields
}
WAVService synthesises text or SSML into 48 kHz mono PCM16 WAV files asynchronously.
func (*WAVService) Create ¶
func (s *WAVService) Create(ctx context.Context, opts WAVOptions) (*WAVJob, error)
Create starts a job; poll it with Get and fetch the file with Download.
func (*WAVService) Delete ¶
Delete cancels unfinished work, or deletes a finished file. A finished job keeps its charge.
func (*WAVService) Download ¶
func (s *WAVService) Download(ctx context.Context, jobID string) (io.ReadCloser, error)
Download returns the finished WAV file. The caller closes it. Before the job completes it fails with job_not_complete (409).
type WebhookEvent ¶
type WebhookEvent struct {
// Event is one of the Event* constants.
Event string `json:"event"`
// ID is the same for every URL of one event.
ID string `json:"id"`
// CreatedAt is a Unix time in seconds.
CreatedAt Int64 `json:"createdAt"`
Room *Room `json:"room,omitempty"`
Participant *ParticipantInfo `json:"participant,omitempty"`
Track *TrackInfo `json:"track,omitempty"`
}
WebhookEvent is a node's event about a participant or track. There are no retries: each event is sent once per URL, so make handlers idempotent by ID.
func DecodeWebhook ¶
func DecodeWebhook(body []byte) (*WebhookEvent, error)
DecodeWebhook decodes a webhook body without verifying it. Use Receive for anything you act on.
type WebhookOptions ¶
type WebhookOptions struct {
// RPCURL is a Solana RPC endpoint. Env: SOLANA_NETWORK_HOST_HTTP.
RPCURL string
// ContractAddress of the registry program. Env: SOLANA_CONTRACT_ADDRESS.
ContractAddress string
// RegistryAuthority of the node registry. Env: SOLANA_REGISTRY_AUTHORITY.
RegistryAuthority string
// HTTPClient calls the RPC; http.DefaultClient when nil.
HTTPClient *http.Client
}
WebhookOptions configure a WebhookReceiver. Empty fields fall back to environment variables, then to dTelecom's mainnet registry.
type WebhookReceiver ¶
type WebhookReceiver struct {
// contains filtered or unexported fields
}
WebhookReceiver verifies node webhooks. Each node signs a delivery with its own Ed25519 key; the receiver checks that the key belongs to a registered node, then the signature and the body hash. It needs outbound access to the Solana RPC once per node and caches the result. It is safe for concurrent use.
func NewWebhookReceiver ¶
func NewWebhookReceiver(opts WebhookOptions) (*WebhookReceiver, error)
NewWebhookReceiver returns a receiver for the registry in opts.
func (*WebhookReceiver) Receive ¶
func (w *WebhookReceiver) Receive(ctx context.Context, body []byte, authHeader string) (*WebhookEvent, error)
Receive verifies a webhook: body is the raw POST body, authHeader the Authorization header.
func (*WebhookReceiver) ReceiveRequest ¶
func (w *WebhookReceiver) ReceiveRequest(r *http.Request) (*WebhookEvent, error)
ReceiveRequest verifies the webhook in r and returns its event.