tokbox

package module
v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2019 License: MIT Imports: 17 Imported by: 0

README

Tokbox Golang GoDoc

This Library is for creating sessions and tokens for the Tokbox Video, Voice & Messaging Platform. See Tokbox website

It is a hybrid library (supports Google App Engine and Stand-Alone binary). It supports multi-threading for faster generation of tokens.

Install

go get -u github.com/pjebs/tokbox

Usage

import "github.com/pjebs/tokbox"

//setup the api to use your credentials
tb := tokbox.New("<my api key>","<my secret key>")

//create a session
session, err := tb.NewSession("", tokbox.P2P) //no location, peer2peer enabled

//create a token
token, err := session.Token(tokbox.Publisher, "", tokbox.Hours24) //type publisher, no connection data, expire in 24 hours

//Or create multiple tokens
tokens := session.Tokens(5, true, tokbox.Publisher, "", tokbox.Hours24) //5 tokens, multi-thread token generation, type publisher, no connection data, expire in 24 hours. Returns a []string

See the unit test for a more detailed example.

Settings

type MediaMode string

const (
	/**
	 * The session will send streams using the OpenTok Media Router.
	 */
	MediaRouter MediaMode = "disabled"
	/**
	* The session will attempt to send streams directly between clients. If clients cannot connect
	* due to firewall restrictions, the session uses the OpenTok TURN server to relay streams.
	 */
	P2P = "enabled"
)

MediaMode is the second argument in NewSession method.

type Role string

const (
	/**
	* A publisher can publish streams, subscribe to streams, and signal.
	 */
	Publisher Role = "publisher"
	/**
	* A subscriber can only subscribe to streams.
	 */
	Subscriber = "subscriber"
	/**
	* In addition to the privileges granted to a publisher, in clients using the OpenTok.js 2.2
	* library, a moderator can call the <code>forceUnpublish()</code> and
	* <code>forceDisconnect()</code> method of the Session object.
	 */
	Moderator = "moderator"
)

Role is the first argument in Token method.

const (
	Days30  = 2592000 //30 * 24 * 60 * 60
	Weeks1  = 604800 //7 * 24 * 60 * 60
	Hours24 = 86400  //24 * 60 * 60
	Hours2  = 7200   //60 * 60 * 2
	Hours1  = 3600   //60 * 60
)

Expiration value forms the third argument in Token method. It dictates how long a token is valid for. The unit is in (seconds) up to a maximum of 30 days.

Methods

func (t *Tokbox) NewSession(location string, mm MediaMode) (*Session, error)

Creates a new session or returns an error. A session represents a 'virtual chat room' where participants can 'sit in' and communicate with one another. A session can not be deregistered. If you no longer require the session, just discard it's details.

location string

The location setting is optional, and generally you should keep it as "". This setting is an IP address that TokBox will use to situate the session in its global network. If no location hint is passed in (which is recommended), the session uses a media server based on the location of the first client connecting to the session. Pass a location hint in only if you know the general geographic region (and a representative IP address) and you think the first client connecting may not be in that region. If you need to specify an IP address, replace location with an IP address that is representative of the geographical location for the session. (Tokbox - REST API reference)

mm MediaMode

P2P will direct clients to transfer video-audio data between each other directly (if possible).

MediaRouter directs data to go through Tokbox's Media Router servers. Integrates Intelligent Quality Control technology to improve user-experience (albeit at higher pricing). (Tokbox - REST API reference)

func (s *Session) Token(role Role, connectionData string, expiration int64) (string, error)

Generates a token for a corresponding session. Returns a string representing the token value or returns an error. A token represents a 'ticket' allowing participants to 'sit in' a session. The permitted range of activities is determined by the role setting.

role Role

Publisher - allows participant to broadcast their own audio and video feed to other participants in the session. They can also listen to and watch broadcasts by other members of the session.

Subscriber - allows participants to only listen to and watch broadcasts by other participants in the session with Publisher rights.

connectionData string

connectionData - Extra arbitrary data that can be read by other clients. (Tokbox - Generating Tokens)

expiration int64

expiration - How long the token is valid for. The unit is in (seconds) up to a maximum of 30 days. See above for built-in enum values, or use your own.

func (s *Session) Tokens(n int, multithread bool, role Role, connectionData string, expiration int64) []string

Generates multiple (n) tokens in one go. Returns a []string. All tokens generated have the same settings as dictated by role, connectionData and expiration. See above for more details. Since the function repeatedly calls the Token method, any error in token generation is ignored. Therefore it may be prudent to check if the length of the returned []string matches n.

multithread bool

If true, the function strives to generate the tokens concurrently (if multiple CPU cores are available). Preferred if many, many, many tokens need to be generated in one go.

Credits:

(This library is based on the older tokbox library – no longer in active development)

https://github.com/cioc/tokbox by Charles Cary

Documentation

Overview

Author: majianyu Create Date: 2019-06-06 Description: version V1.0

Index

Constants

View Source
const (
	Days30  = 2592000 //30 * 24 * 60 * 60
	Weeks1  = 604800  //7 * 24 * 60 * 60
	Hours24 = 86400   //24 * 60 * 60
	Hours2  = 7200    //60 * 60 * 2
	Hours1  = 3600    //60 * 60
)
View Source
const (
	/**
	* A publisher can publish streams, subscribe to streams, and signal.
	 */
	Publisher Role = "publisher"
	/**
	* A subscriber can only subscribe to streams.
	 */
	Subscriber = "subscriber"
	/**
	* In addition to the privileges granted to a publisher, in clients using the OpenTok.js 2.2
	* library, a moderator can call the <code>forceUnpublish()</code> and
	* <code>forceDisconnect()</code> method of the Session object.
	 */
	Moderator = "moderator"
)

Variables

This section is empty.

Functions

func CheckResponseError

func CheckResponseError(resp *http.Response) error

Types

type Archive

type Archive struct {
	CreatedAt  int64       `json:"createdAt"`
	Duration   int         `json:"duration"`
	HasAudio   bool        `json:"hasAudio"`
	HasVideo   bool        `json:"hasVideo"`
	ID         string      `json:"id"` // archive id
	Name       string      `json:"name"`
	OutputMode string      `json:"outputMode"`
	ProjectID  int         `json:"projectId"`
	Reason     string      `json:"reason"`
	Resolution string      `json:"resolution"`
	SessionID  string      `json:"sessionId"`
	Size       int         `json:"size"`
	Status     string      `json:"status"`
	URL        interface{} `json:"url"`
}

func (*Archive) GetUrl

func (this *Archive) GetUrl() string

func (*Archive) Json

func (this *Archive) Json() string

type ArchiveOptions

type ArchiveOptions struct {
	Offset    int    `url:"offset,omitempty"`     // default 0
	Count     int    `url:"count,omitempty"`      // default 50
	SessionId string `url:"session_id,omitempty"` // default null, get all archive list
}

url query options

type ArchiveReq

type ArchiveReq struct {
	SessionID  string `json:"sessionId"`
	HasAudio   bool   `json:"hasAudio"`
	HasVideo   bool   `json:"hasVideo"`
	Layout     Layout `json:"layout"`
	Name       string `json:"name"`       // (Optional) The name of the archive (for your own identification)
	OutputMode string `json:"outputMode"` // composed (default) | individual
	Resolution string `json:"resolution"` // 640x480 (default) | 1280x720
}

request body

func DefaultArchiveReq

func DefaultArchiveReq(sessionId, name string) ArchiveReq

type ArchiveResponse

type ArchiveResponse struct {
	Count int       `json:"count"`
	Items []Archive `json:"items"`
}

response

func (*ArchiveResponse) Json

func (this *ArchiveResponse) Json() string

type ArchiveService

type ArchiveService interface {
	Start(ArchiveReq) (resp *Archive, err error)
	Stop(archiveId string) (resp *Archive, err error)
	List(interface{}) (resp *ArchiveResponse, error error)
	Get(archiveId string) (resp *Archive, err error)
	Delete(archiveId string) error
}

type ArchiveServiceOp

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

func (*ArchiveServiceOp) Delete

func (this *ArchiveServiceOp) Delete(archiveId string) (err error)

func (*ArchiveServiceOp) Get

func (this *ArchiveServiceOp) Get(archiveId string) (resp *Archive, err error)

func (*ArchiveServiceOp) List

func (this *ArchiveServiceOp) List(options interface{}) (resp *ArchiveResponse, err error)

func (*ArchiveServiceOp) Start

func (this *ArchiveServiceOp) Start(data ArchiveReq) (resp *Archive, err error)

func (*ArchiveServiceOp) Stop

func (this *ArchiveServiceOp) Stop(archiveId string) (resp *Archive, err error)

type Layout

type Layout struct {
	Type       string `json:"type" `                // bestFit | custom | horizontalPresentation | pip | verticalPresentation
	Stylesheet string `json:"stylesheet,omitempty"` // only used with type == custom
}

type MediaMode

type MediaMode string
const (
	/**
	 * The session will send streams using the OpenTok Media Router.
	 */
	MediaRouter MediaMode = "disabled"
	/**
	* The session will attempt send streams directly between clients. If clients cannot connect
	* due to firewall restrictions, the session uses the OpenTok TURN server to relay streams.
	 */
	P2P = "enabled"
)

type ResponseError

type ResponseError struct {
	Code        int    `json:"code"`
	Message     string `json:"message"`
	Description string `json:"description"`
}

func (ResponseError) Error

func (this ResponseError) Error() string

type Role

type Role string

type Session

type Session struct {
	SessionId      string  `json:"session_id"`
	ProjectId      string  `json:"project_id"`
	PartnerId      string  `json:"partner_id"`
	CreateDt       string  `json:"create_dt"`
	SessionStatus  string  `json:"session_status"`
	MediaServerURL string  `json:"media_server_url"`
	T              *Tokbox `json:"-"`
}

func (*Session) Token

func (s *Session) Token(role Role, connectionData string, expiration int64) (string, error)

func (*Session) Tokens

func (s *Session) Tokens(n int, multithread bool, role Role, connectionData string, expiration int64) []string

type StreamItem

type StreamItem struct {
	ID            string `json:"id"`
	SessionID     string `json:"sessionId"`
	ProjectID     int    `json:"projectId"`
	CreatedAt     int64  `json:"createdAt"`
	UpdatedAt     int64  `json:"updatedAt"`
	Resolution    string `json:"resolution"`
	BroadcastUrls struct {
		Hls  string `json:"hls"`
		Rtmp struct {
			Foo struct {
				ServerURL  string `json:"serverUrl"`
				StreamName string `json:"streamName"`
				Status     string `json:"status"`
			} `json:"foo"`
			Bar struct {
				ServerURL  string `json:"serverUrl"`
				StreamName string `json:"streamName"`
				Status     string `json:"status"`
			} `json:"bar"`
		} `json:"rtmp"`
	} `json:"broadcastUrls"`
	Status string `json:"status"`
}

type StreamOption

type StreamOption struct {
	Offset    int    `url:"offset,omitempty"`
	Count     int    `url:"count,omitempty"`
	SessionID string `url:"session_id,omitempty"`
}

type StreamResponse

type StreamResponse struct {
	Count int          `json:"count"`
	Items []StreamItem `json:"items"`
}

func (StreamResponse) Json

func (this StreamResponse) Json() string

type StreamService

type StreamService interface {
	List(interface{}) (resp *StreamResponse, error error)
}

type StreamServiceOp

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

func (*StreamServiceOp) List

func (this *StreamServiceOp) List(options interface{}) (resp *StreamResponse, err error)

type Tokbox

type Tokbox struct {
	Client *http.Client

	BetaUrl string         //Endpoint for Beta Programs
	Archive ArchiveService // Archive sdk
	Stream  StreamService  // Stream sdk
	// contains filtered or unexported fields
}

func New

func New(apikey, partnerSecret string) *Tokbox

func (*Tokbox) CreateAndDo

func (this *Tokbox) CreateAndDo(method, path string, data, options, resource interface{}) error

func (*Tokbox) Delete

func (this *Tokbox) Delete(path string, resource, options interface{}) error

func (*Tokbox) Do

func (this *Tokbox) Do(req *http.Request, v interface{}) error

func (*Tokbox) Get

func (this *Tokbox) Get(path string, resource, options interface{}) error

func (*Tokbox) NewRequest

func (this *Tokbox) NewRequest(method, urlStr string, body, options interface{}) (*http.Request, error)

func (*Tokbox) NewSession

func (t *Tokbox) NewSession(location string, mm MediaMode, ctx ...context.Context) (*Session, error)

Creates a new tokbox session or returns an error. See README file for full documentation: https://github.com/pjebs/tokbox NOTE: ctx must be nil if *not* using Google App Engine

func (*Tokbox) Post

func (this *Tokbox) Post(path string, data, resource interface{}) error

func (*Tokbox) Put

func (this *Tokbox) Put(path string, data, resource interface{}) error

Jump to

Keyboard shortcuts

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