@tivio/sdk-react
v10.1.0
Published
@tivio/sdk-react provides everything which is necessary (components, data hooks etc.) to build a custom React application above Tivio Studio. You can comfortably manage all you videos, settings such as application's screens and rows and also monetization
Readme
@tivio/sdk-react
@tivio/sdk-react provides everything which is necessary (components, data hooks etc.) to build a custom React application above Tivio Studio. You can comfortably manage all you videos, settings such as application's screens and rows and also monetization settings in the administration of Tivio Studio while having the freedom to build your own application.
Installation
Install @tivio/sdk-react along with its peer dependencies
npm i react@18 react-dom@18 @tivio/sdk-react
# or
yarn add react@18 react-dom@18 @tivio/sdk-reactInitialization
Put Tivio Provider at the top level of your application:
import { TivioProvider } from '@tivio/sdk-react'
const config = {
secret: 'XXXXXXXXXX',
}
function App({children}) {
return (
<TivioProvider conf={config}>
{children}
</TivioProvider>
)
}Authentication
A logged-in user can access more features, such as making purchases. In order to authenticate a user with Tivio, use the setUser() method.
Verification of the user against 3rd party auth servers is implemented per customer.
import { setUser } from '@tivio/sdk-react'
// Log in
// Payload is specific per customer
// A common use-case is sending an auth token inside the payload, which Tivio can use to verify the user
await setUser('userId', { token: 'xxx'})
// Log out
await setUser(null)Single Sign-On (SSO) across subdomains
If you want to enable Single Sign-On (SSO) for all subdomains under the same parent domain, you can specify the customTokenCookiesDomain in the configuration object.
import type { Config } from '@tivio/sdk-react'
const config: Config = {
// ... other required tivio config properties
customTokenCookiesDomain: 'example.com' // allows SSO across example.com, app.example.com, admin.example.com, etc.
};Player
You can choose whether you will use complete player component provided by Tivio or you will wrap your existing player with the Tivio Player Wrapper.
Tivio Player component
import { useTivioData } from '@tivio/sdk-react'
const PlayerExample = () => {
const bundle = useTivioData()
if (!bundle?.components?.WebPlayer) {
return <p>Loading...</p>
}
return (
<>
<div
style={{
height: 720,
width: 1280,
}}
>
<bundle.components.WebPlayer
id="player1"
className="web-player"
source="/videos/xxxxxxxxxxxxxxxxxxxx" // dynamically change this based on video you want to play
/>
</div>
</>
)
}Player wrapper
Player wrapper is the way how you can enhance your video player with Tivio features, such Tivio Ads. In order to start using Tivio player wrapper, wrap your player methods with PlayerWrapper, start using PlayerWrapper's methods instead of them to control your playback and start sending player events to Tivio PlayerWrapper.
Wrap your player methods with Tivio player wrapper
import { useTivioReadyData } from '@tivio/sdk-react'
function CustomPlayer() {
const tivioData = useTivioReadyData()
useEffect(() => {
if (tivioData) {
// If your app uses multiple player instances, use different Tivio player wrapper for each
// distinguished by playerWrapperId
const playerWrapper = tivio.getPlayerWrapper({ playerWrapperId: 'PLAYER_1' })
// Pass your player methods to Tivio player wrapper
playerWrapper.register({
play: () => {
// Un-pause your player
},
pause: () => {
// Pause your player
},
seekTo: (ms: number) => {
// Seek to position in milliseconds using your player
},
setSource: (videoSource: InputSource) => {
// Send this video source to your player to load it
},
})
}
}, [tivioData])
}Start using Tivio player wrapper methods to control playback
// Channel source metadata, such as channel name, epg start and epg end are necessary
// for TV ad segment detection and application of ad strategies
const source = new ChannelSource(
'https://channel_prima_hd.m3u8',
{
// here put any additional metadata, for your use.
// This object will not be touched by Tivio
},
// channel name
// can also be prima hd, prima_hd, prima, Prima, PRIMA, etc.
// we will normalize it to snake case and add '_hd' if necessary
'Prima HD',
// program name
'Dr. House',
// description (optional)
'Episode about Dr. House being awesome',
// EPG start
new Date('2021-12-10T12:00:00'),
// EPG end
new Date('2021-12-10T13:40:00'),
)
// Send source to player
playerWrapper.onSourceChanged(source)
// Un-pause player
playerWrapper.play()
// Pause player
playerWrapper.pause()
}Start reporting player events to Tivio
// Report that source is playing
playerWrapper.onStateChanged('playing')
// Report that source is paused
playerWrapper.onStateChanged('paused')
// Report that source stopped playing
playerWrapper.onPlaybackEnded()
playerWrapper.onStateChanged('idle')
// Report video progress
playerWrapper.onTimeChanged(ms)
}Start reporting playback-related errors to Tivio
// Report that video failed to load (e.g. due to a wrong URI)
playerWrapper.onLoadError(new Error('video failed to load'))
// Report that video failed during playback (e.g. due to bad connection, corrupted chunks of stream video etc.)
// This type of error may be auto-recoverable
playerWrapper.onError(new Error('playback error'))
}JavaScript Methods for Rendering Players
renderWebPlayer
The renderWebPlayer method allows you to render a Tivio player outside of React components. This is useful for scenarios where you need to integrate the player into non-React environments.
The method is asynchronous and returns a VideoController instance that provides comprehensive control over playback.
import { renderWebPlayer } from '@tivio/sdk-react'
// Example usage
const videoController = await renderWebPlayer(
document.getElementById('video-player'),
{
id: 'player-main',
source: 'videos/ID',
}
)
// Control playback
videoController.play()
videoController.pause()
videoController.togglePause()
// Seeking
videoController.seekToAbsolutePosition(30000) // Seek to 30 seconds
videoController.seekBy(5000) // Seek forward by 5 seconds
videoController.seekToPercent(50) // Seek to 50% of video
videoController.seekToLive() // Seek to live position (for live streams)
// Volume control
videoController.changeVolume(0.8) // Set volume to 80%
videoController.volumeUp() // Increase volume by 5%
videoController.volumeDown() // Decrease volume by 5%
videoController.mute()
videoController.unmute()
videoController.toggleMute()
// Get current source
console.log('Current source:', videoController.currentSource)
// Change source
videoController.setSource('videos/newVideoId') // Change to a different video
videoController.setSource('tvChannels/channelId') // Change to a TV channel
videoController.setSource(null) // Stop playback
// Event handling
videoController.addEventListener('video_unit_ended', () => {
console.log('Video playback ended')
})
videoController.addEventListener('timeupdate', (currentTime) => {
console.log('Current time:', currentTime)
})
// Cleanup
videoController.destroy()VideoController Methods
The VideoController returned by renderWebPlayer provides the following methods:
Playback Control:
play()- Resume playback from paused statepause()- Pause the current playbacktogglePause()- Toggle between play and pause statesreplay()- Replay the current video from the beginningretry()- Retry playback if it failed to start
Seeking:
seekToAbsolutePosition(ms: number)- Seek to absolute position in millisecondsseekBy(ms: number)- Seek relative to current positionseekToPercent(percentage: number)- Seek to percentage of video durationseekToLive()- Seek to live position (for live streams)
Volume Control:
changeVolume(value: number)- Set volume (0-1)volumeUp()- Increase volume by 5%volumeDown()- Decrease volume by 5%mute()- Mute audiounmute()- Unmute audiotoggleMute()- Toggle mute state
Source Management:
setSource(source: WebPlayerProps['source'])- Change the current source to a new one (updates player props)currentSource- Currently playing source or null if no source is loaded
Source Types
The Tivio player supports different types of sources:
VOD_EXTERNAL - External video-on-demand content from third-party URLs
- Used for playing videos that are hosted outside of Tivio's infrastructure
- Supports various streaming protocols (HLS, DASH, MP4)
- Example usage:
const externalSource = {
type: SourceType.VOD_EXTERNAL,
url: 'https://example.com/video.m3u8',
sourcePlayMode: SourcePlayMode.ON_DEMAND,
poster: 'https://example.com/poster.jpg',
name: 'External Video',
autoplay: false,
continuePositionMs: 10000, // Start at 10 seconds (optional)
}Source Play Modes
The sourcePlayMode property determines how the content is played:
- ON_DEMAND - Standard video playback with full seeking capabilities
- LIVE - Live stream mode with no seeking
- HYBRID - Combines LIVE with seeking
Using setSource with VideoController
The setSource method allows you to dynamically change what's playing:
// Change to a different video
videoController.setSource('videos/newVideoId')
// Change to an external video
videoController.setSource({
type: SourceType.VOD_EXTERNAL,
url: 'https://example.com/video.mpd',
sourcePlayMode: SourcePlayMode.ON_DEMAND,
name: 'External Video'
})
// Change to a TV channel
videoController.setSource('tvChannels/channelId')
// Stop playback
videoController.setSource(null)The setSource method is particularly useful for:
- Play next
- Implementing playlists
- Dynamic content loading
Event Handling:
addEventListener(event: string, callback: (value: T) => void)- Add event listenerremoveEventListener(event: string, callback: (value: T) => void)- Remove event listener
Utility:
destroy()- Destroy player and clean up resources
Playback Events
The VideoController emits various events that you can listen to:
// Video state changes
videoController.addEventListener('statechange', (state) => {
console.log('Player state:', state) // 'playing', 'paused', 'idle'
})
// Time updates
videoController.addEventListener('timeupdate', (currentTime) => {
console.log('Current time:', currentTime)
})
// Video ended
videoController.addEventListener('video_unit_ended', () => {
console.log('Video playback ended')
})
// Duration changes
videoController.addEventListener('durationchange', (duration) => {
console.log('Video duration:', duration)
})
// Volume changes
videoController.addEventListener('volumechange', ({ muted, volume }: { muted: boolean, volume: number }) => {
console.log('Volume changed:', { muted, volume })
})
// Buffering state
videoController.addEventListener('bufferingchange', (isBuffering) => {
console.log('Buffering:', isBuffering)
})
// Errors
videoController.addEventListener('error', (error) => {
console.error('Playback error:', error)
})WebPlayerProps
The WebPlayerProps interface defines the properties that can be passed to the Tivio WebPlayer component. Here's a comprehensive overview of available properties:
Required Properties
id(string): Unique identifier for the player instance. This is required and must be unique across your application.
Source Properties
source(optional): The video or channel source to play. Can be:VideoPath(string): Path to a video (e.g., "videos/VIDEO_ID")ChannelPath(string): Path to a TV channel (e.g., "tvChannels/CHANNEL_ID")SourceParams(object): Complex source parametersnull: No source (player will be idle)
Callback Properties
onEnded(optional): Callback function called when video playback endsonProgress(optional): Callback function for video progress events
Layout Properties
className(optional): CSS class name for the player containerisSameSizeAsParent(optional): Iftrue, the player will inherit the width and height of its parent element
Playback Control Properties
autoplay(optional, default:false): Whether to start playback automatically. Note that autoplay may be blocked by browsers before user interactioncanReplay(optional, default:true): Whether to show replay functionalitydoNotSaveWatchPosition(optional): Iftrue, the player won't save the watch positiondisablePlayNext(optional): Iftrue, the player won't automatically play the next video when current video ends
Visual Properties
showMarkers(optional, default:false): Whether to show video markersmarkerColor(optional): Color for video markers (CSS color value)showTvStreamType(optional): Whether to show TV stream type indicatorshowCookiesSettings(optional): Whether to show cookies settingsshowOsd(optional, default:true): Whether to show the On-Screen Display (OSD)showBufferingSpinner(optional, default:true): Whether to show buffering spinner
Audio Properties
isMutedByDefault(optional): Iftrue, the player starts muted but can be unmuted
Keyboard Shortcuts Properties
enableKeyboardShortcuts(optional, default:true): Whether to enable keyboard shortcutscustomShortcuts(optional): Custom keyboard shortcuts configuration:{ toggleFullscreen: number[], // Array of key codes togglePause: number[], toggleMute: number[], jumpForward: number[], jumpBack: number[], volumeUp: number[], volumeDown: number[] }
Ad Block Properties
checkAdBlock(optional, default:false): Whether to check for ad blockers and show warnings
Data hooks
Gets information about current user.
useUser: () => {
user: User | null
error: string | null
isInitialized: boolean
}useRowsInScreen hook
Gets array of Rows objects of specific screen and subscribes to its changes.
/**
* Use rows in screen
* @param screenId - screen id (from studio.tiv.io)
* @param options - subscription options
*/
useRowsInScreen: (screenId: string, options?: PaginationOptions) => {
pagination: PaginationInterface<Row> | null
error: Error | null
}useItemsInRow hook
Gets array of row items objects of specific row and subscribes to its changes.
/**
* Use row items
* @param rowId - row ID
* @param options - subscription options
*/
useItemsInRow: (rowId: string, options?: SubscribeToItemsInRowOptions) => {
pagination: PaginationInterface<ItemInRow> | null
error: Error | null
}useVideo hook
Gets Video object and subscribes to its changes.
/**
* Use video
* @param videoId - video id
*/
useVideo: (videoId: string) => {
error: string | null;
data: Video | null;
}useTaggedVideos hook
Gets videos with given tag IDs.
/**
* Use tagged videos
* @param tagIds - tag ids
* @param options - subscription options
* @public
*/
useTaggedVideos: (tagIds: string[], options?: SubscribeToItemsInRowOptions) => {
pagination: PaginationInterface<Video> | null
error: Error | null
}