@tivio/sdk-react 11.0.1 → 12.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md.bak DELETED
@@ -1,623 +0,0 @@
1
- # @tivio/sdk-react
2
-
3
- @tivio/sdk-react provides everything which is necessary (components, data hooks etc.) to build a custom React application
4
- above Tivio Studio. You can comfortably manage all you videos, settings such as application's screens and rows and also monetization
5
- settings in the administration of Tivio Studio while having the freedom to build your own application.
6
-
7
- ## Installation
8
-
9
- Install @tivio/sdk-react along with its peer dependencies
10
- ```sh
11
- npm i react@18 react-dom@18 @tivio/sdk-react
12
- # or
13
- yarn add react@18 react-dom@18 @tivio/sdk-react
14
- ```
15
-
16
- ## Initialization
17
-
18
- Put Tivio Provider at the top level of your application:
19
-
20
- ``` javascript
21
- import { TivioProvider } from '@tivio/sdk-react'
22
-
23
- const config = {
24
- secret: 'XXXXXXXXXX',
25
- }
26
-
27
- function App({children}) {
28
- return (
29
- <TivioProvider conf={config}>
30
- {children}
31
- </TivioProvider>
32
- )
33
- }
34
- ```
35
-
36
- ## Authentication
37
-
38
- A logged-in user can access more features, such as making purchases. In order to authenticate a user with Tivio, use the `setUser()` method.
39
-
40
- Verification of the user against 3rd party auth servers is implemented per customer.
41
-
42
- ```typescript
43
- import { setUser } from '@tivio/sdk-react'
44
-
45
- // Log in
46
-
47
- // Payload is specific per customer
48
- // A common use-case is sending an auth token inside the payload, which Tivio can use to verify the user
49
- await setUser('userId', { token: 'xxx'})
50
-
51
- // Log out
52
- await setUser(null)
53
- ```
54
-
55
- ## Single Sign-On (SSO) across subdomains
56
- 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.
57
- ``` javascript
58
- import type { Config } from '@tivio/sdk-react'
59
-
60
- const config: Config = {
61
- // ... other required tivio config properties
62
- customTokenCookiesDomain: 'example.com' // allows SSO across example.com, app.example.com, admin.example.com, etc.
63
- };
64
- ```
65
-
66
- ## Player
67
-
68
- You can choose whether you will use complete player component provided by Tivio or you will wrap your existing player
69
- with the Tivio Player Wrapper.
70
-
71
- ### Tivio Player component
72
-
73
- ```javascript
74
- import { useTivioData } from '@tivio/sdk-react'
75
-
76
- const PlayerExample = () => {
77
- const bundle = useTivioData()
78
-
79
- if (!bundle?.components?.WebPlayer) {
80
- return <p>Loading...</p>
81
- }
82
-
83
- return (
84
- <>
85
- <div
86
- style={{
87
- height: 720,
88
- width: 1280,
89
- }}
90
- >
91
- <bundle.components.WebPlayer
92
- id="player1"
93
- className="web-player"
94
- source="/videos/xxxxxxxxxxxxxxxxxxxx" // dynamically change this based on video you want to play
95
- />
96
- </div>
97
- </>
98
- )
99
- }
100
- ```
101
-
102
- ### Player wrapper
103
-
104
- Player wrapper is the way how you can enhance your video player with Tivio features, such Tivio Ads. In order to start
105
- using Tivio player wrapper, wrap your player methods with PlayerWrapper, start using PlayerWrapper's methods
106
- instead of them to control your playback and start sending player events to Tivio PlayerWrapper.
107
-
108
- #### Wrap your player methods with Tivio player wrapper
109
-
110
- ```javascript
111
- import { useTivioReadyData } from '@tivio/sdk-react'
112
-
113
- function CustomPlayer() {
114
- const tivioData = useTivioReadyData()
115
-
116
- useEffect(() => {
117
- if (tivioData) {
118
- // If your app uses multiple player instances, use different Tivio player wrapper for each
119
- // distinguished by playerWrapperId
120
- const playerWrapper = tivio.getPlayerWrapper({ playerWrapperId: 'PLAYER_1' })
121
-
122
- // Pass your player methods to Tivio player wrapper
123
- playerWrapper.register({
124
- play: () => {
125
- // Un-pause your player
126
- },
127
- pause: () => {
128
- // Pause your player
129
- },
130
- seekTo: (ms: number) => {
131
- // Seek to position in milliseconds using your player
132
- },
133
- setSource: (videoSource: InputSource) => {
134
- // Send this video source to your player to load it
135
- },
136
- })
137
- }
138
- }, [tivioData])
139
- }
140
- ```
141
-
142
- #### Start using Tivio player wrapper methods to control playback
143
-
144
- ```javascript
145
- // Channel source metadata, such as channel name, epg start and epg end are necessary
146
- // for TV ad segment detection and application of ad strategies
147
- const source = new ChannelSource(
148
- 'https://channel_prima_hd.m3u8',
149
- {
150
- // here put any additional metadata, for your use.
151
- // This object will not be touched by Tivio
152
- },
153
- // channel name
154
- // can also be prima hd, prima_hd, prima, Prima, PRIMA, etc.
155
- // we will normalize it to snake case and add '_hd' if necessary
156
- 'Prima HD',
157
- // program name
158
- 'Dr. House',
159
- // description (optional)
160
- 'Episode about Dr. House being awesome',
161
- // EPG start
162
- new Date('2021-12-10T12:00:00'),
163
- // EPG end
164
- new Date('2021-12-10T13:40:00'),
165
- )
166
-
167
- // Send source to player
168
- playerWrapper.onSourceChanged(source)
169
-
170
- // Un-pause player
171
- playerWrapper.play()
172
-
173
- // Pause player
174
- playerWrapper.pause()
175
- }
176
- ```
177
-
178
- #### Start reporting player events to Tivio
179
-
180
- ```javascript
181
- // Report that source is playing
182
- playerWrapper.onStateChanged('playing')
183
-
184
- // Report that source is paused
185
- playerWrapper.onStateChanged('paused')
186
-
187
- // Report that source stopped playing
188
- playerWrapper.onPlaybackEnded()
189
- playerWrapper.onStateChanged('idle')
190
-
191
- // Report video progress
192
- playerWrapper.onTimeChanged(ms)
193
- }
194
- ```
195
-
196
- #### Start reporting playback-related errors to Tivio
197
-
198
- ```javascript
199
- // Report that video failed to load (e.g. due to a wrong URI)
200
- playerWrapper.onLoadError(new Error('video failed to load'))
201
-
202
- // Report that video failed during playback (e.g. due to bad connection, corrupted chunks of stream video etc.)
203
- // This type of error may be auto-recoverable
204
- playerWrapper.onError(new Error('playback error'))
205
- }
206
- ```
207
-
208
- ## JavaScript Methods for Rendering Players
209
-
210
- ### renderWebPlayer
211
-
212
- 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.
213
-
214
- The method is asynchronous and returns a VideoController instance that provides comprehensive control over playback.
215
-
216
- ```typescript
217
- import { renderWebPlayer } from '@tivio/sdk-react'
218
-
219
- // Example usage
220
- const videoController = await renderWebPlayer(
221
- document.getElementById('video-player'),
222
- {
223
- id: 'player-main',
224
- source: 'videos/ID',
225
- }
226
- )
227
-
228
- // Control playback
229
- videoController.play()
230
- videoController.pause()
231
- videoController.togglePause()
232
-
233
- // Seeking
234
- videoController.seekToAbsolutePosition(30000) // Seek to 30 seconds
235
- videoController.seekBy(5000) // Seek forward by 5 seconds
236
- videoController.seekToPercent(50) // Seek to 50% of video
237
- videoController.seekToLive() // Seek to live position (for live streams)
238
-
239
- // Volume control
240
- videoController.changeVolume(0.8) // Set volume to 80%
241
- videoController.volumeUp() // Increase volume by 5%
242
- videoController.volumeDown() // Decrease volume by 5%
243
- videoController.mute()
244
- videoController.unmute()
245
- videoController.toggleMute()
246
-
247
- // Get current source
248
- console.log('Current source:', videoController.currentSource)
249
-
250
- // Change source
251
- videoController.setSource('videos/newVideoId') // Change to a different video
252
- videoController.setSource('tvChannels/channelId') // Change to a TV channel
253
- videoController.setSource(null) // Stop playback
254
-
255
- // Event handling
256
- videoController.addEventListener('video_unit_ended', () => {
257
- console.log('Video playback ended')
258
- })
259
-
260
- videoController.addEventListener('timeupdate', (currentTime) => {
261
- console.log('Current time:', currentTime)
262
- })
263
-
264
- // Cleanup
265
- videoController.destroy()
266
- ```
267
-
268
- #### VideoController Methods
269
-
270
- The VideoController returned by `renderWebPlayer` provides the following methods:
271
-
272
- **Playback Control:**
273
- - `play()` - Resume playback from paused state
274
- - `pause()` - Pause the current playback
275
- - `togglePause()` - Toggle between play and pause states
276
- - `replay()` - Replay the current video from the beginning
277
- - `retry()` - Retry playback if it failed to start
278
-
279
- **Seeking:**
280
- - `seekToAbsolutePosition(ms: number)` - Seek to absolute position in milliseconds
281
- - `seekBy(ms: number)` - Seek relative to current position
282
- - `seekToPercent(percentage: number)` - Seek to percentage of video duration
283
- - `seekToLive()` - Seek to live position (for live streams)
284
-
285
- **Volume Control:**
286
- - `changeVolume(value: number)` - Set volume (0-1)
287
- - `volumeUp()` - Increase volume by 5%
288
- - `volumeDown()` - Decrease volume by 5%
289
- - `mute()` - Mute audio
290
- - `unmute()` - Unmute audio
291
- - `toggleMute()` - Toggle mute state
292
-
293
- **Source Management:**
294
- - `setSource(source: WebPlayerProps['source'])` - Change the current source to a new one (updates player props)
295
- - `currentSource` - Currently playing source or null if no source is loaded
296
-
297
- #### Source Types
298
-
299
- The Tivio player supports different types of sources:
300
-
301
- **VOD_EXTERNAL** - External video-on-demand content from third-party URLs
302
- - Used for playing videos that are hosted outside of Tivio's infrastructure
303
- - Supports various streaming protocols (HLS, DASH, MP4)
304
- - Example usage:
305
- ```typescript
306
- const externalSource = {
307
- type: SourceType.VOD_EXTERNAL,
308
- url: 'https://example.com/video.m3u8',
309
- sourcePlayMode: SourcePlayMode.ON_DEMAND,
310
- poster: 'https://example.com/poster.jpg',
311
- name: 'External Video',
312
- autoplay: false,
313
- continuePositionMs: 10000, // Start at 10 seconds (optional)
314
- }
315
- ```
316
-
317
- #### Source Play Modes
318
-
319
- The `sourcePlayMode` property determines how the content is played:
320
-
321
- - **ON_DEMAND** - Standard video playback with full seeking capabilities
322
- - **LIVE** - Live stream mode with no seeking
323
- - **HYBRID** - Combines LIVE with seeking
324
-
325
- #### Using setSource with VideoController
326
-
327
- The `setSource` method allows you to dynamically change what's playing:
328
-
329
- ```typescript
330
- // Change to a different video
331
- videoController.setSource('videos/newVideoId')
332
-
333
- // Change to an external video
334
- videoController.setSource({
335
- type: SourceType.VOD_EXTERNAL,
336
- url: 'https://example.com/video.mpd',
337
- sourcePlayMode: SourcePlayMode.ON_DEMAND,
338
- name: 'External Video'
339
- })
340
-
341
- // Change to a TV channel
342
- videoController.setSource('tvChannels/channelId')
343
-
344
- // Stop playback
345
- videoController.setSource(null)
346
- ```
347
-
348
- The `setSource` method is particularly useful for:
349
- - Play next
350
- - Implementing playlists
351
- - Dynamic content loading
352
-
353
- **Event Handling:**
354
- - `addEventListener(event: string, callback: (value: T) => void)` - Add event listener
355
- - `removeEventListener(event: string, callback: (value: T) => void)` - Remove event listener
356
-
357
- **Utility:**
358
- - `destroy()` - Destroy player and clean up resources
359
-
360
- #### Playback Events
361
-
362
- The VideoController emits various events that you can listen to:
363
-
364
- ```typescript
365
- // Video state changes
366
- videoController.addEventListener('statechange', (state) => {
367
- console.log('Player state:', state) // 'playing', 'paused', 'idle'
368
- })
369
-
370
- // Time updates
371
- videoController.addEventListener('timeupdate', (currentTime) => {
372
- console.log('Current time:', currentTime)
373
- })
374
-
375
- // Video ended
376
- videoController.addEventListener('video_unit_ended', () => {
377
- console.log('Video playback ended')
378
- })
379
-
380
- // Duration changes
381
- videoController.addEventListener('durationchange', (duration) => {
382
- console.log('Video duration:', duration)
383
- })
384
-
385
- // Volume changes
386
- videoController.addEventListener('volumechange', ({ muted, volume }: { muted: boolean, volume: number }) => {
387
- console.log('Volume changed:', { muted, volume })
388
- })
389
-
390
- // Buffering state
391
- videoController.addEventListener('bufferingchange', (isBuffering) => {
392
- console.log('Buffering:', isBuffering)
393
- })
394
-
395
- // Errors
396
- videoController.addEventListener('error', (error) => {
397
- console.error('Playback error:', error)
398
- })
399
- ```
400
-
401
- ## WebPlayerProps
402
-
403
- The `WebPlayerProps` interface defines the properties that can be passed to the Tivio WebPlayer component. Here's a comprehensive overview of available properties:
404
-
405
- ### Required Properties
406
-
407
- - **`id`** (string): Unique identifier for the player instance. This is required and must be unique across your application.
408
-
409
- ### Source Properties
410
-
411
- - **`source`** (optional): The video or channel source to play. Can be:
412
- - `VideoPath` (string): Path to a video (e.g., "videos/VIDEO_ID")
413
- - `ChannelPath` (string): Path to a TV channel (e.g., "tvChannels/CHANNEL_ID")
414
- - `SourceParams` (object): Complex source parameters
415
- - `null`: No source (player will be idle)
416
-
417
- ### Callback Properties
418
-
419
- - **`onEnded`** (optional): Callback function called when video playback ends
420
- - **`onProgress`** (optional): Callback function for video progress events
421
-
422
- ### Layout Properties
423
-
424
- - **`className`** (optional): CSS class name for the player container
425
- - **`isSameSizeAsParent`** (optional): If `true`, the player will inherit the width and height of its parent element
426
-
427
- ### Playback Control Properties
428
-
429
- - **`autoplay`** (optional, default: `false`): Whether to start playback automatically. Note that autoplay may be blocked by browsers before user interaction
430
- - **`canReplay`** (optional, default: `true`): Whether to show replay functionality
431
- - **`doNotSaveWatchPosition`** (optional): If `true`, the player won't save the watch position
432
- - **`disablePlayNext`** (optional): If `true`, the player won't automatically play the next video when current video ends
433
-
434
- ### Visual Properties
435
-
436
- - **`showMarkers`** (optional, default: `false`): Whether to show video markers
437
- - **`markerColor`** (optional): Color for video markers (CSS color value)
438
- - **`showTvStreamType`** (optional): Whether to show TV stream type indicator
439
- - **`showCookiesSettings`** (optional): Whether to show cookies settings
440
- - **`showOsd`** (optional, default: `true`): Whether to show the On-Screen Display (OSD)
441
- - **`showBufferingSpinner`** (optional, default: `true`): Whether to show buffering spinner
442
-
443
- ### Audio Properties
444
-
445
- - **`isMutedByDefault`** (optional): If `true`, the player starts muted but can be unmuted
446
-
447
- ### Keyboard Shortcuts Properties
448
-
449
- - **`enableKeyboardShortcuts`** (optional, default: `true`): Whether to enable keyboard shortcuts
450
- - **`customShortcuts`** (optional): Custom keyboard shortcuts configuration:
451
- ```typescript
452
- {
453
- toggleFullscreen: number[], // Array of key codes
454
- togglePause: number[],
455
- toggleMute: number[],
456
- jumpForward: number[],
457
- jumpBack: number[],
458
- volumeUp: number[],
459
- volumeDown: number[]
460
- }
461
- ```
462
-
463
- ### Ad Block Properties
464
-
465
- - **`checkAdBlock`** (optional, default: `false`): Whether to check for ad blockers and show warnings
466
-
467
- ## Data hooks
468
- Gets information about current user.
469
-
470
- ```ts
471
- useUser: () => {
472
- user: User | null
473
- error: string | null
474
- isInitialized: boolean
475
- }
476
- ```
477
-
478
- ### useRowsInScreen hook
479
- Gets array of Rows objects of specific screen and subscribes to its changes.
480
-
481
- ```ts
482
- /**
483
- * Use rows in screen
484
- * @param screenId - screen id (from studio.tiv.io)
485
- * @param options - subscription options
486
- */
487
- useRowsInScreen: (screenId: string, options?: PaginationOptions) => {
488
- pagination: PaginationInterface<Row> | null
489
- error: Error | null
490
- }
491
- ```
492
-
493
- ### useItemsInRow hook
494
- Gets array of row items objects of specific row and subscribes to its changes.
495
-
496
- ```ts
497
- /**
498
- * Use row items
499
- * @param rowId - row ID
500
- * @param options - subscription options
501
- */
502
- useItemsInRow: (rowId: string, options?: SubscribeToItemsInRowOptions) => {
503
- pagination: PaginationInterface<ItemInRow> | null
504
- error: Error | null
505
- }
506
- ```
507
-
508
- ### useVideo hook
509
-
510
- Gets Video object and subscribes to its changes.
511
-
512
- ```ts
513
- /**
514
- * Use video
515
- * @param videoId - video id
516
- */
517
- useVideo: (videoId: string) => {
518
- error: string | null;
519
- data: Video | null;
520
- }
521
- ```
522
-
523
- ### useTaggedVideos hook
524
- Gets videos with given tag IDs.
525
-
526
- ```ts
527
- /**
528
- * Use tagged videos
529
- * @param tagIds - tag ids
530
- * @param options - subscription options
531
- * @public
532
- */
533
- useTaggedVideos: (tagIds: string[], options?: SubscribeToItemsInRowOptions) => {
534
- pagination: PaginationInterface<Video> | null
535
- error: Error | null
536
- }
537
- ```
538
-
539
- ### useVoucher hook
540
-
541
- Activates a voucher for the current user. Reading vouchers directly from the client is
542
- forbidden, so the hook does not fetch the voucher — calling `activate()` invokes the
543
- `activateVoucher` cloud function, which detects on its own whether the code is a single-use
544
- or a multi-use voucher.
545
-
546
- After a successful activation the `voucher` object exposes server-provided metadata
547
- (`voucherInfo`, `videoId`, `subscriptionsToShow`) as flat attributes. Until the voucher is
548
- initialized, `voucher` is `null`.
549
-
550
- ```ts
551
- /**
552
- * Use voucher
553
- * @param voucherId - voucher code entered by the user
554
- */
555
- useVoucher: (voucherId: string) => {
556
- /**
557
- * Triggers the `activateVoucher` cloud function for the current user.
558
- * On success, `activationSuccess` becomes `true` and `voucher` is populated
559
- * with the activation metadata.
560
- */
561
- activate: () => Promise<void>
562
- voucher: {
563
- organizationId: string | null
564
- isInitialized: boolean
565
- /** Public, server-safe metadata about the activated voucher. */
566
- voucherInfo: VoucherInfoPublic | null
567
- /** Video the voucher relates to, when its document references one (`voucherInfo.videoId`). */
568
- videoId?: string
569
- /** Monetizations to offer when the voucher does not fully cover the content. */
570
- subscriptionsToShow: PurchasableMonetization[]
571
- } | null
572
- error: Error | BadRequestError | null
573
- activationSuccess: boolean
574
- }
575
- ```
576
-
577
- `voucherInfo` is a discriminated union by `type`:
578
-
579
- ```ts
580
- type VoucherInfoPublic = VoucherInfoSubscriptionPublic | VoucherInfoTransactionPublic
581
-
582
- interface VoucherInfoBasePublic {
583
- id: string
584
- isExpired: boolean
585
- status: 'NEW' | 'USED' | 'FULFILLED'
586
- /** True when the voucher fully covers the content (no further payment needed). */
587
- fullDiscount?: boolean
588
- /** Video the voucher relates to, when its document references one. Present for both types. */
589
- videoId?: string
590
- }
591
-
592
- interface VoucherInfoSubscriptionPublic extends VoucherInfoBasePublic {
593
- type: 'subscription'
594
- name: string
595
- benefits: string[]
596
- frequency?: MONETIZATION_FREQUENCY
597
- }
598
-
599
- interface VoucherInfoTransactionPublic extends VoucherInfoBasePublic {
600
- type: 'transaction'
601
- name: string
602
- videoId: string
603
- cover: string
604
- description: string
605
- }
606
- ```
607
-
608
- When activation fails, `error` may be a `BadRequestError` whose `details.reason` explains why:
609
-
610
- ```ts
611
- type BadRequestError = Error & {
612
- details?: {
613
- reason?:
614
- | 'DOES_NOT_EXIST'
615
- | 'EXPIRED'
616
- | 'ALREADY_USED'
617
- | 'ALREADY_USED_BY_CURRENT_USER'
618
- | 'LIMIT_REACHED'
619
- | 'FULFILLED'
620
- | 'INVALID_VOUCHER_TYPE'
621
- }
622
- }
623
- ```