### Build the Vega Video Sample App: npm install and npm run build:app
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Install dependencies and build the app to generate .vpkg files. The installation can take several minutes. Run 'npm install' again if build errors occur due to missing Java or Python prerequisites.
```bash
npm install
```
```bash
npm run build:app
```
--------------------------------
### Usage example for AccountLoginWrapper
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/AccountLoginWrapper.md
Usage example for the AccountLoginWrapper. Shows how to start the service, read the persisted login status, update it, and stop the service. The component instance is obtained from the platform.
```ts
import { onStartService, onStopService, AccountLoginWrapperInstance } from './AccountLoginWrapper';
import { IComponentInstance } from '@amazon-devices/react-native-kepler';
const component: IComponentInstance = /* obtained from the platform */;
// Start the account-login service
await onStartService(component);
// Read the persisted login status
const status = await AccountLoginWrapperInstance.getAccountLoginStatus();
console.log(status.status); // StatusType.SIGNED_IN | SIGNED_OUT
// Update login status
await AccountLoginWrapperInstance.updateStatus(true);
// Stop the service
await onStopService();
```
--------------------------------
### Usage example for IAPManager
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/iap.md
Shows how to trigger a purchase for the monthly subscription and reconcile prior purchases on app start using IAPManager and IAPConstants.
```ts
import { IAPManager } from './src/iap/utils/IAPManager';
import { IAPConstants } from './src/iap/IAPConstants';
// Trigger a purchase for the monthly subscription
IAPManager.triggerPurchase(IAPConstants.MONTHLY_SUBSCRIPTION_SKU);
// Reconcile prior purchases on app start
IAPManager.getPurchaseUpdates();
```
--------------------------------
### Usage example for utility functions
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/utils.md
Imports and demonstrates the focus manager, formatTime, throttleFactory, translate, getSelectedLocale, and WithSuspense. The example shows how to register and restore focus, format time, translate a key, and use the throttle factory.
```TypeScript
import { focusManager } from './src/utils/FocusManager';
import { formatTime, throttleFactory } from './src/utils/commonFunctions';
import { translate, getSelectedLocale } from './src/utils/translationHelper';
import { WithSuspense } from './src/utils/WithSuspense';
focusManager.registerFocusCallback('details', () => console.log('restore'));
focusManager.restoreFocus('details');
console.log(formatTime(3725)); // '01:02:05'
console.log(translate('settings', getSelectedLocale().code));
const throttled = throttleFactory(1000, () => console.log('tick'));
throttled.throttledFunction();
```
--------------------------------
### Usage example for createDataProvider
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/data-provider.md
Shows how to instantiate the provider with playlist data and call its methods. The example uses a playlist named 'Latest Hits' and demonstrates getContent, getContentByCriteria with a search keyword, and getRelatedContent.
```ts
import { createDataProvider } from './src/services/dataProviderFactory';
const playlists = [
{
playlistName: 'Latest Hits',
medias: getLatestHits(),
},
];
const dataProvider = createDataProvider(playlists);
const all = await dataProvider.getContent();
const results = await dataProvider.getContentByCriteria({ searchKeyword: 'Nyla' });
const related = await dataProvider.getRelatedContent(playlists[0].medias[0]);
```
--------------------------------
### Run the app on Vega Virtual Device: vega virtual-device start and vega run-app
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Run the app on the Vega Virtual Device (VVD). Start the VVD, then install and launch the app with the command for your architecture: aarch64 for Mac M-series, x86_64 for x86_64 devices. The generated VPKG files are in the build folder.
```bash
vega virtual-device start
```
```bash
vega run-app build/aarch64-release/keplervideoapp_aarch64.vpkg
```
```bash
vega run-app build/x86_64-release/keplervideoapp_x86_64.vpkg
```
--------------------------------
### Usage example for data providers
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/data-providers.md
Shows how to import and use `VideoSources`, `VideoFileTypes`, `getClassics`, `getRotator`, and `AutoRotatorData` in a consumer module.
```ts
import { VideoSources, VideoFileTypes } from './src/data/videos';
import { getClassics } from './src/data/local/classics';
import { getRotator } from './src/data/local/rotator';
import { AutoRotatorData } from './src/data';
const hlsSource = VideoSources[VideoFileTypes.HLS];
const classics = getClassics();
const heroItems = AutoRotatorData;
```
--------------------------------
### NavBar and MediaContent Usage Example
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-components.md
Example usage of NavBar and MediaContent components with navigation items and media content.
```APIDOC
## NavBar and MediaContent Usage Example
### Description
Example usage of NavBar and MediaContent components with navigation items and media content.
### Code Example
```tsx
import { NavBar } from './src/blocks/components/NavBar';
import { MediaContent } from './src/blocks/components/MediaContent';
import { NavBarItemAction } from './src/blocks/components/NavigationBarItem';
const navItems: NavBarItemAction[] = [
{ iconUri: require('./home.png'), text: 'Home', type: 'category', onPress: () => {} },
{ iconUri: require('./search.png'), text: 'Search', type: 'search', onPress: () => {} },
];
openDetails(mediaItem)} />
```
```
--------------------------------
### Usage example
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-helpers.md
Shows how to import and use the helper functions: convertSecondsToFormattedTime, getLayout, getErrorMessage, and scaleUxToDp.
```TypeScript
import {
convertSecondsToFormattedTime,
getLayout,
getErrorMessage,
} from './src/blocks/helpers';
import { scaleUxToDp } from './src/blocks/helpers/pixelUtils';
console.log(convertSecondsToFormattedTime(3725)); // '01:02:05'
const layout = getLayout(playlists); // 'shoveler' | 'grid'
const width = scaleUxToDp(100); // 100 * (screenHeight/1080)
```
--------------------------------
### Store usage example with initializeStore and dispatch
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/redux-store.md
Shows how to initialize the store, dispatch actions like addToWatchList and setCountryCode, and select from videoDetailSelectors. Requires the store to be initialized before dispatching.
```ts
import { initializeStore, RootState, AppDispatch } from './src/store';
import { addToWatchList, videoDetailSelectors } from './src/store/videoDetail/videoDetailSlice';
import { setCountryCode } from './src/store/settings/SettingsSlice';
const store = await initializeStore();
store.dispatch(addToWatchList('169327'));
store.dispatch(setCountryCode({ label: 'US', value: 'en-US', code: 'en' }));
const watchList = videoDetailSelectors.watchList(store.getState() as RootState);
```
--------------------------------
### Get base OS with getBaseOs()
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Calls getBaseOs() asynchronously to retrieve the base OS build. The example shows the result in a comment; actual output may differ.
```typescript
DeviceInfo.getBaseOs().then((baseOs) => {
// "Vega"
});
```
--------------------------------
### Usage example for NavBar and MediaContent
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-components.md
Shows how to import and use NavBar and MediaContent components with navigation items and media content.
```tsx
import { NavBar } from './src/blocks/components/NavBar';
import { MediaContent } from './src/blocks/components/MediaContent';
import { NavBarItemAction } from './src/blocks/components/NavigationBarItem';
const navItems: NavBarItemAction[] = [
{ iconUri: require('./home.png'), text: 'Home', type: 'category', onPress: () => {} },
{ iconUri: require('./search.png'), text: 'Search', type: 'search', onPress: () => {} },
];
openDetails(mediaItem)} />
```
--------------------------------
### Integrate Vega-supported react-native-netinfo
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Integrate Vega-supported react-native-netinfo. Add the package dependency to package.json, add the network service to manifest.toml, add the net-info privilege, run npm install, then import the NetInfo components and use the fetch method to get network status. The fetch method returns a promise that resolves to a state object with isConnected, type, and details properties.
```json
"dependencies": {
...
"@amazon-devices/keplerscript-netmgr-lib": "~2.0.2",
}
```
```text
[[wants.service]]
id = "com.amazon.network.service"
```
```text
[needs]
[[needs.privilege]]
id="com.amazon.network.privilege.net-info"
```
```typescript
import {
NetInfoStateType,
fetch,
} from '@amazon-devices/keplerscript-netmgr-lib';
```
```typescript
fetch().then((state) => {
console.log('is connected? ' + state.isConnected);
if (state.type === NetInfoStateType.wifi) {
console.log('ssid is ' + state.details.ssid);
}
});
```
--------------------------------
### Usage example for AppOverrideMediaControlHandler
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/AppOverrideMediaControlHandler.md
Shows how to instantiate the handler with and without client override, and set it as the media control focus on a VideoPlayer.
```typescript
import { AppOverrideMediaControlHandler } from './src/utils/AppOverrideMediaControlHandler';
import { VideoPlayer } from '@amazon-devices/react-native-w3cmedia';
const videoPlayer = new VideoPlayer();
// Let the default handler manage playback (clientOverrideNeeded = false)
const defaultHandler = new AppOverrideMediaControlHandler(videoPlayer, false);
// Take over playback control (clientOverrideNeeded = true)
const customHandler = new AppOverrideMediaControlHandler(videoPlayer, true);
await videoPlayer.setMediaControlFocus(componentInstance, customHandler);
```
--------------------------------
### Usage example with useGetContentDataProvider
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-hooks.md
Shows how to use useGetContentDataProvider with createDataProvider to render content, handling LOADING and ERROR states.
```tsx
import { useGetContentDataProvider } from './src/blocks/hooks/useDataProvider';
import { createDataProvider } from './src/services/dataProviderFactory';
const dataProvider = createDataProvider(playlists);
const { data, dataStatus, error, retry } = useGetContentDataProvider(dataProvider);
if (dataStatus === 'LOADING') return ;
if (dataStatus === 'ERROR') return ;
return ;
```
--------------------------------
### Usage example for config and theme APIs
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/config.md
Shows how to import and use the configuration flags and theme builders together. Creates a theme, retrieves card dimensions, and conditionally enables personalization based on the flag.
```ts
import {
isContentPersonalizationEnabled,
isDpadControllerSupported,
isRunningOnSimulator,
} from './src/config/AppConfig';
import { createTheme } from './src/styles/ThemeBuilders';
import { getVerticalCardDimensionsMd } from './src/styles/ThemeAccessors';
const theme = createTheme();
const { width, height } = getVerticalCardDimensionsMd(theme);
if (isContentPersonalizationEnabled()) {
// enable content personalization
}
const dpad = isDpadControllerSupported();
```
--------------------------------
### onStartDataRefreshService(componentInstance: IComponentInstance): Promise
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/headless-services.md
Starts the DataRefreshService by delegating to the singleton DataRefreshService.onStart method. This registers content-personalization handlers for the given component instance.
```APIDOC
## onStartDataRefreshService(componentInstance: IComponentInstance): Promise
### Description
Starts the DataRefreshService by delegating to the singleton DataRefreshService.onStart method. This registers content-personalization handlers for the given component instance.
### Method
Function call
### Signature
```ts
onStartDataRefreshService(componentInstance: IComponentInstance): Promise
```
### Parameters
- **componentInstance** (IComponentInstance) - Required - The platform-provided component instance.
### Returns
- **Promise** - Resolves when the service has started.
### Usage Example
```ts
import { onStartDataRefreshService } from './src/headless/DataRefreshService';
import { IComponentInstance } from '@amazon-devices/react-native-kepler';
const component: IComponentInstance = /* platform-provided */;
await onStartDataRefreshService(component);
```
```
--------------------------------
### Import and render VideoPlayerUI with seek example
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/w3cmedia-mediacontrols.md
Imports VideoPlayerUI and seek from the mediacontrols module, renders the component with required props, and demonstrates seeking forward by 10 seconds.
```tsx
import VideoPlayerUI from './src/w3cmedia/mediacontrols/VideoPlayerUI';
import { seek, throttleSeek } from './src/w3cmedia/mediacontrols/PlaybackControls';
navigation.goBack()}
title={titleData.title}
setCaptionStatus={setCaptionStatus}
setSelectedCaptionInVideoPlayer={setSelectedCaption}
bifFrameImagesRef={bifRef}
videoData={titleData}
/>;
// Seek forward 10 seconds
seek(10, videoRef);
```
--------------------------------
### Define search data JSON for KVATestData.json
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Two JSON examples for the KVATestData.json file. The structure defines an array of playlists, each with a playlistName and a medias array containing video metadata fields. The example file includes required fields like uri, categories, channelID, posterUrl, format, uhd, secure, and rentAmount, plus optional fields such as drm_scheme, drm_license_uri, textTrack, acodec, and vcodec.
```json
[
{
"medias": [
{
"uri": "string",
"categories": ["string"],
"channelID": "string",
"posterUrl": "string",
"format": "string",
"drm_scheme": "string (optional)",
"drm_license_uri": "string (optional)",
"textTrack": "TextTrack[] (optional)",
"uhd": "boolean",
"secure": "boolean",
"acodec": "string (optional)",
"vcodec": "string (optional)",
"rentAmount": "string"
}
],
"playlistName": "string"
}
]
```
```json
[
{
"playlistName": "Test file ",
"medias": [
{
"id": "13342393",
"title": "Sample file",
"description": "Hey Everyone, travel a little south of Uvita and across from Playa Ocochal (Ojochal), and then take a left at the sign advertising the Tilapa El Pavon Restaurant. On the way to the restaurant (which we have a video about and also recommend), on the left hand side, you should see the sign for La Cascada el Pavon (Turkey Waterfall). We highly suggest you stop and take the very short hike down to the waterfall and check it out. Way COOL! Don't take our word for it - Check out this video. Pura Vida!",
"duration": 105,
"thumbnail": "http://le1.cdn01.net/videos/0000133/0133420/thumbs/0133420__005f.jpg",
"posterUrl": "http://le1.cdn01.net/videos/0000133/0133420/thumbs/0133420__005f.jpg",
"videoUrl": "https://edge-vod-media.cdn01.net/encoded/0000133/0133420/video_1880k/G0CXIG1LX.mp4?source=firetv&channelID=13454",
"categories": ["Costa Rica Islands"],
"channelID": "13454",
"rating": "2.5",
"mediaType": "video",
"mediaSourceType": "url",
"format": "MP4",
"secure": false,
"uhd": true,
"rentAmount": "135"
}
]
}
]
```
--------------------------------
### Usage example combining useCarouselData and useMediaControls
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/hooks.md
Shows how to use useCarouselData and useMediaControls together in a component. Imports both hooks and demonstrates their usage with sample arguments.
```TypeScript
import { useCarouselData } from './src/hooks/useCarouselData';
import { useMediaControls } from './src/w3cmedia/mediacontrols/types/useMediaControls';
const { visibleData, isFullyLoaded } = useCarouselData({
data: titles,
isPriorityRow: true,
initialTilesToRender: 3,
reportFullyDrawn: () => console.log('drawn'),
});
const [showControls, setShowControls] = useState(false);
const { handleShowControlsOnKeyEvent, cancelTimer } = useMediaControls(showControls, setShowControls);
```
--------------------------------
### FrameImageSource and FrameImageOffset types with usage example
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/bif-services.md
Defines the frame source interface and the offset type used to locate frames in a BIF file, followed by a usage example showing how to obtain a frame image source from a BIF URL games/cdn, retrieve a base64 image at a specific millisecond, and fall back to per-second JPEGs.
```ts
interface FrameImageSource {
clearCache(): void;
getImageData(positionMillis: number): Uint8Array | null;
getBase64Image(positionMillis: number): string | null;
}
export type { FrameImageSource };
```
```ts
interface FrameImageOffset {
positionMillis: number;
offsetBytes: number;
}
export type { FrameImageOffset };
```
```ts
import { getBifFrameImageSource, getImageForVideoSecond } from './src/services/bif/bifService';
const source = await getBifFrameImageSource('https://cdn.example.com/movie.bif');
if (source) {
const base64 = source.getBase64Image(1590000); // frame at 26:30
source.clearCache();
} else {
console.warn('BIF file was invalid');
}
// Trickplay fallback using per-second JPEGs
const url = getImageForVideoSecond(90, 'https://cdn.example.com/trickplays/movie/');
```
--------------------------------
### AccountLoginWrapper Module Exports
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/AccountLoginWrapper.md
Module-level exports and usage examples for the AccountLoginWrapper module, including service start/stop functions and methods on the singleton instance.
```APIDOC
## onStartService(componentInstance: IComponentInstance): Promise
### Description
Starts the account-login service by delegating to the singleton `AccountLoginWrapper` instance's `onStart` method. This is registered as the `com.amazondeveloper.keplervideoapp.interface.provider::onStartService` headless entry point.
### Parameters
- **componentInstance** (IComponentInstance) - Required - The component instance obtained from the platform.
### Returns
- Promise - Resolves when the service has started.
## onStopService(): Promise
### Description
Stops the account-login service by delegating to the singleton `AccountLoginWrapper` instance's `onStop` method. This is registered as the `com.amazondeveloper.keplervideoapp.interface.provider::onStopService` headless entry point.
### Returns
- Promise - Resolves when the service has stopped.
## AccountLoginWrapperInstance.getAccountLoginStatus(): Promise<{ status: StatusType }>
### Description
Reads the persisted login status from the singleton `AccountLoginWrapper` instance.
### Returns
- Promise<{ status: StatusType }> - An object containing the current login status, which can be `StatusType.SIGNED_IN` or `StatusType.SIGNED_OUT`.
## AccountLoginWrapperInstance.updateStatus(signedIn: boolean): Promise
### Description
Updates the persisted login status on the singleton `AccountLoginWrapper` instance.
### Parameters
- **signedIn** (boolean) - Required - The new login status; `true` for signed in, `false` for signed out.
### Returns
- Promise - Resolves when the status has been updated.
```
--------------------------------
### Usage example for SearchPageScreen and SearchResultsScreen
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-screens.md
Shows how to import and use both screen components together. The SearchPageScreen navigates to SearchResults on submit, and SearchResultsScreen uses a data provider and search keyword.
```tsx
import { SearchPageScreen } from './src/blocks/screen/SearchPageScreen';
import { SearchResultsScreen } from './src/blocks/screen/SearchResultsScreen';
import { createDataProvider } from './src/services/dataProviderFactory';
navigation.navigate('SearchResults', { searchKeyword: keyword })}
backgroundColor="black"
/>
openDetails(mediaItem)}
/>
```
--------------------------------
### Integrate @amazon-devices/react-native-device-info
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Steps to integrate the react-native-device-info library: add the dependency to package.json, run npm install, then import the DeviceInfo module or destructured functions like getBaseOs.
```json
{
"dependencies": {
"...": "",
"@amazon-devices/react-native-device-info": "~2.0.0"
}
}
```
```bash
npm install
```
```typescript
import DeviceInfo from '@amazon-devices/react-native-device-info';
// or ES6+ destructured imports
import { getBaseOs } from '@amazon-devices/react-native-device-info';
```
--------------------------------
### Usage example for DataRefreshService headless service
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/headless-services.md
Shows how to import and use the onStartDataRefreshService and onStopDataRefreshService functions with a component instance. The onStart call registers content-personalization handlers, and the service runs in the background until onStop is called.
```TypeScript
import { onStartDataRefreshService, onStopDataRefreshService } from './src/headless/DataRefreshService';
import { IComponentInstance } from '@amazon-devices/react-native-kepler';
const component: IComponentInstance = /* platform-provided */;
await onStartDataRefreshService(component); // registers content-personalization handlers
// ... service runs in background ...
await onStopDataRefreshService(component);
```
--------------------------------
### EPG Sync Tasks Usage Example
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/epg-sync-tasks.md
Imports EPG sync tasks and channel tuner handler. Force-syncs channel and program lineups with progress callbacks, then runs the full headless task. The commented line shows how to set the tuner handler on a ChannelServer.
```TypeScript
import doEpgSyncTask from './src/livetv/task/EpgSyncTask';
import { ingestChannelLineup, ingestProgramLineup } from './src/livetv/task/EpgSyncTask';
import channelTunerHandler from './src/livetv/channelTunerHandler';
// Force-sync latest EPG data with progress reporting
const version = new Date(Date.now()).toISOString();
try {
await ingestChannelLineup(version, (p) => console.log(`channels ${p * 100}%`));
await ingestProgramLineup(version, (p) => console.log(`programs ${p * 100}%`));
} catch (e) {
console.error('EPG sync failed', e);
}
// Run the full headless task
await doEpgSyncTask();
// Provide the tuner handler to a ChannelServer
// ChannelServerComponent2.setChannelHandlerForComponent(channelTunerHandler, componentInstance);
```
--------------------------------
### Run the app on Vega OS Fire TV Stick: vega run-app armv7
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Install and launch the app on the Vega OS Fire TV Stick. Use the armv7 VPKG file that was generated for Fire TV Stick.
```bash
vega run-app build/armv7-release/keplervideoapp_armv7.vpkg
```
--------------------------------
### Integrate @reduxjs/toolkit and configure store
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Integration steps for Redux Toolkit: add dependencies, install, create a counter slice with actions and selector, then configure the store and infer RootState and AppDispatch types.
```json
{
"dependencies": {
"...": "",
"@reduxjs/toolkit": "2.2.4",
"react-redux": "9.1.2"
}
}
```
```bash
npm install
```
```typescript
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '../../app/store';
```
```typescript
// Define a type for the slice state.
interface CounterState {
value: number;
}
// Define the initial state using that type.
const initialState: CounterState = {
value: 0,
};
export const counterSlice = createSlice({
name: 'counter',
// `createSlice` infers the state type from the `initialState` argument.
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
// Use the PayloadAction type to declare the contents of `action.payload`.
incrementByAmount: (state, action: PayloadAction) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } =
counterSlice.actions;
// Other code such as selectors can use the imported `RootState` type.
export const selectCount = (state: RootState) => state.counter.value;
export default counterSlice.reducer;
```
```typescript
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';
```
```typescript
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
// Infer the `RootState` and `AppDispatch` types from the store itself.
export type RootState = ReturnType;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}.
export type AppDispatch = typeof store.dispatch;
```
--------------------------------
### onStart method implementation
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/AccountLoginWrapper.md
Implementation of onStart. Calls setupAccountLoginServer and returns a resolved promise.
```ts
onStart(componentInstance: IComponentInstance): Promise {
this.setupAccountLoginServer(componentInstance);
return Promise.resolve();
}
```
--------------------------------
### setupEventListeners()
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Sets up event listeners for the video player.
```APIDOC
## setupEventListeners()
### Description
Sets up event listeners for the video player.
### Return
void
```
--------------------------------
### setupAccountLoginServer method implementation
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/AccountLoginWrapper.md
Implementation of setupAccountLoginServer. Obtains the server and registers the login handler for the component. Failures are caught and logged.
```ts
setupAccountLoginServer(componentInstance: IComponentInstance) {
try {
this.accountLoginServer = accountLoginServerComponent.getOrMakeServer();
} catch (err) {
this.accountLoginServer = undefined;
console.error('setupAccountLoginServer failed creating account login server: ', err);
return;
}
try {
this.accountLoginServer?.setHandlerForComponent(this.createAccountLoginHandler(), componentInstance);
} catch (err) {
console.error('setupAccountLoginServer failed to set handler: ', err);
}
}
```
--------------------------------
### DataRefreshService
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/headless-services.md
Implements HeadlessServiceInterface. On start, registers three Content Personalization handlers for the given component instance.
```APIDOC
## Class: DataRefreshService
### Description
Implements HeadlessServiceInterface. On start, registers three Content Personalization handlers on the ContentPersonalizationServer for the given component instance.
### Methods
#### onStart(componentInstance: IComponentInstance): Promise
- **Description**: Registers the content entitlements, customer list entries, and playback events handlers for the component instance, then resolves.
- **Parameters**:
- `componentInstance` (IComponentInstance) - Required - The component instance for which handlers are registered.
- **Returns**: Promise
#### onStop(_componentInstance: IComponentInstance): Promise
- **Description**: Always resolves. No cleanup is performed.
- **Parameters**:
- `_componentInstance` (IComponentInstance) - Required - The component instance (unused).
- **Returns**: Promise
```
--------------------------------
### Use mock source functions for lineup, programs, entitlement, and playback event
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/mock-sources.md
Import the mock functions and call them to retrieve mock data: channel lineup and programs with pagination parameters, plus a content entitlement and a playback event. The channel lineup and program functions are asynchronous; the entitlement and playback event are synchronous.
```ts
import { getMockedChannelLineup, getMockedPrograms } from './src/livetv/mock/MockSource';
import {
getMockContentEntitlement,
getDefaultMockPlaybackEvent,
} from './src/personalization/mock/ContentPersonalizationMocks';
const channels = await getMockedChannelLineup(0, 1000);
const programs = await getMockedPrograms(0, 1000);
const entitlement = getMockContentEntitlement();
const playbackEvent = getDefaultMockPlaybackEvent();
```
--------------------------------
### DataProviderInput type
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/types.md
Defines the input variants for data provider operations: fetching all content, searching by criteria, and getting related content.
```ts
export type DataProviderInput =
| { type: 'getContent' }
| { type: 'search_by_criteria'; searchCriteria: DataProviderFilteringCriteria }
| { type: 'get_related_content'; mediaItem: MediaItem; playlistName?: string };
```
--------------------------------
### preBufferVideo(componentInstance?: IComponentInstance)
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Destroys existing video elements, creates a new VideoPlayer if needed, sets global.gmedia, optionally sets KMC focus, initializes the player, sets up event listeners, disables autoplay, and loads video elements.
```APIDOC
## preBufferVideo(componentInstance?: IComponentInstance)
### Description
Destroys existing video elements, creates a new VideoPlayer if needed, sets global.gmedia, optionally sets KMC focus with an AppOverrideMediaControlHandler, initializes the player, sets up event listeners, disables autoplay, and loads video elements.
### Parameters
- **componentInstance** (IComponentInstance) - Optional - The component instance for setting media control focus.
### Return
Promise
### Errors
KMC errors and initialization errors are caught and logged; they do not reject the outer promise.
```
--------------------------------
### app.json configuration for entry point names
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/entry-points.md
Defines the app name and sync source name used in index.js. The displayName is 'Vegavideoapp'.
```json
{
"name": "com.amazondeveloper.keplervideoapp.main",
"syncSourceName": "com.amazondeveloper.keplervideoapp.sync_source",
"displayName": "Vegavideoapp"
}
```
--------------------------------
### initializeStore()
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/redux-store.md
Initializes the Redux store with the four reducers, hydrates from AsyncStorage, and subscribes to persist state changes.
```APIDOC
## initializeStore()
### Description
Initializes the Redux store with the four reducers (videoDetail, settings, search, focus), hydrates from AsyncStorage under the key `reduxState`, and subscribes to persist state on every change.
### Method
initializeStore
### Endpoint
initializeStore()
### Parameters
None
### Return
- **Promise** - The configured store instance.
### Behavior
- Reads preloaded state from AsyncStorage (`loadState` reads `reduxState`).
- Configures the store with the specified reducers.
- Subscribes to store changes and saves state to AsyncStorage (`saveState` writes `reduxState`).
- Errors reading/writing state are caught and logged.
### Exports
- `store` - The configured store instance (assigned on initialization).
- `RootState` - Inferred root state type.
- `AppDispatch` - Inferred dispatch type.
```
--------------------------------
### Integrate react-native-async-storage
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Add the AsyncStorage dependency and override to package.json, then run npm install。导入 AsyncStorage 后,使用 setItem 存储序列化的 JSON 值,使用 getItem 读取并解析,注意处理保存和读取错误。
```json
{
"dependencies": {
...
"@react-native-async-storage/async-storage": "npm:@amazon-devices/react-native-async-storage__async-storage@~2.0.0"
}
"overrides": {
"@react-native-async-storage/async-storage": "npm:@amazon-devices/react-native-async-storage__async-storage@~2.0.0"
}
}
```
```bash
import AsyncStorage from '@react-native-async-storage/async-storage';
```
```typescript
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem('my-key', jsonValue);
} catch (e) {
// saving error
}
};
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('my-key');
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
// error reading value
}
};
```
--------------------------------
### Integrate lodash isEqual
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Add the lodash dependency to package.json 。 run npm install to reinstall。导入 isEqual 方法后,可用它进行两个对象的深度比较,如示例中 obj1 与 obj2 比较结果为 true。
```json
{
"dependencies": {
...
"lodash": "^4.17.21",
}
}
```
```typescript
import { isEqual } from 'lodash';
```
```typescript
Example;
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
// Comparing two objects.
console.log(isEqual(obj1, obj2));
// Output: true (obj1 and obj2 are deeply equal).
```
--------------------------------
### Pre-buffer video with preBufferVideo
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
The preBufferVideo method as shown in the source. Destroys existing video elements, creates a new VideoPlayer if needed, sets global.gmedia, optionally sets KMC focus with AppOverrideMediaControlHandler, initializes the player, sets up event listeners, disables autoplay, and loads video elements. Errors are caught and logged; they do not reject the outer promise.
```ts
preBufferVideo = useCallback(async (componentInstance?: IComponentInstance) => {
await this.destroyVideoElements();
if (this.videoRef.current == null) {
this.videoRef.current = new VideoPlayer();
}
(global as any).gmedia = this.videoRef.current;
if (componentInstance) {
await this.videoRef.current.setMediaControlFocus(
componentInstance,
new AppOverrideMediaControlHandler(this.videoRef.current as VideoPlayer, false),
);
}
this.videoRef.current.initialize()
.then(() => { this.setupEventListeners(); this.videoRef.current.autoplay = false; this.loadVideoElements(); })
.catch((error) => console.error(error));
}, []);
```
--------------------------------
### HeadlessServiceInterface definition
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/headless-services.md
Defines the contract for headless services with onStart and onStop methods that receive an IComponentInstance. Both methods return a Promise that resolves when the native service start or stop is handled.
```TypeScript
import { IComponentInstance } from '@amazon-devices/react-native-kepler';
export interface HeadlessServiceInterface {
/**
* This function is called when native service onStart is called.
*/
onStart(componentInstance: IComponentInstance): Promise;
/**
* This function is called when native service onStop is called.
*/
onStop(componentInstance: IComponentInstance): Promise;
}
```
--------------------------------
### Integrate @amazon-devices/react-native-vector-icons
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Integration steps for react-native-vector-icons: add the package dependency, install fonts in assets/fonts, import the MaterialIcons component, and render it. Note the color prop uses an invalid syntax (missing quotes).
```json
"dependencies": {
...
"@amazon-devices/react-native-vector-icons": "~2.0.0"
}
```
```javascript
import MaterialIcons from '@amazon-devices/react-native-vector-icons/MaterialIcons';
```
```typescript
```
--------------------------------
### IAPManager class declaration
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/iap.md
Declares the IAPManager class with static methods for triggering purchases, getting purchase updates, handling receipts, and granting purchases. The methods delegate to the IAP SDK and response handler.
```ts
export class IAPManager {
public static triggerPurchase = (sku: string): void;
public static getPurchaseUpdates = () => void;
public static async handleReceipt(userId: string, receipt: Receipt): Promise;
private static async grantPurchase(userId: string, receipt: Receipt): Promise;
}
```
--------------------------------
### DataRefreshService implementation
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/headless-services.md
Implements HeadlessServiceInterface. On start, registers three Content Personalization handlers (content entitlements, customer list entries, playback events) on the ContentPersonalizationServer for the given component instance. Both onStart and onStop return a resolved Promise.
```TypeScript
class DataRefreshService implements HeadlessServiceInterface {
onStart(componentInstance: IComponentInstance): Promise {
ContentPersonalizationServer.setContentEntitlementsHandlerForComponent(
contentEntitlementsHandler, componentInstance,
);
ContentPersonalizationServer.setCustomerListEntriesHandlerForComponent(
customerListEntriesHandler, componentInstance,
);
ContentPersonalizationServer.setPlaybackEventsHandlerForComponent(
playbackEventsHandler, componentInstance,
);
return Promise.resolve();
}
onStop(_componentInstance: IComponentInstance): Promise {
return Promise.resolve();
}
}
```
--------------------------------
### Instantiate and load ShakaPlayer
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/ShakaPlayer.md
Creates a ShakaPlayer with settings and loads a title. The titleData.uri must be an HLS/DASH manifest URL. The load call is wrapped in a try-catch to handle failures.
```TypeScript
import { ShakaPlayer, ShakaPlayerSettings } from './src/w3cmedia/shakaplayer/ShakaPlayer';
import { VideoPlayer } from '@amazon-devices/react-native-w3cmedia';
import { TitleData } from './src/types/TitleData';
const videoRef: React.MutableRefObject = /* ref */;
const settings: ShakaPlayerSettings = {
secure: false,
abrEnabled: false,
abrMaxWidth: 3840,
abrMaxHeight: 2160,
};
const player = new ShakaPlayer(videoRef.current, settings);
try {
player.load(titleData, false); // titleData.uri must be an HLS/DASH manifest URL
} catch (e) {
console.error('Shaka load failed', e);
}
```
--------------------------------
### Integrate Vega-supported react-linear-gradient
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Integrate Vega-supported react-linear-gradient. Add the package dependency to package.json, reinstall dependencies with npm install, then import and add the LinearGradient component in the render block. The component accepts a colors prop and a style prop to display a gradient behind child content.
```json
"dependencies": {
...
"@amazon-devices/react-linear-gradient": "~2.0.0"
}
```
```typescript
import LinearGradient from '@amazon-devices/react-linear-gradient';
```
```typescript
Here Is My Text
```
--------------------------------
### onPlaying()
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Event handler for playing.
```APIDOC
## onPlaying()
### Description
Event handler for playing.
### Return
void
```
--------------------------------
### Integrate react-native-localize
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Add the @amazon-devices/react-native-localize dependency to package.json, then run npm install。需要先创建翻译 JSON 文件(如 en.json),再导入 getCountry 和 getLocales 方法。示例定义了翻译对象、appLocales 数组,并用 getCountry 获取国家、getLocales 过滤支持的语言环境、translate 根据当前语言返回翻译文本。
```json
{
"dependencies": {
...
"@amazon-devices/react-native-localize": "~2.0.0"
}
}
```
```typescript
import {
getCountry,
getLocales,
} from '@amazon-devices/react-native-localize';
import en from '../translations/en.json';
// Other string JSON files
```
```typescript
const translations: any = {
en,
};
export const appLocales = ['en-US'];
export const getCurrentCountry = () => {
return getCountry();
};
export const getAppLocales = () => {
const filteredLocales = getLocales().filter((locale) => {
return appLocales.includes(locale.languageTag);
});
return filteredLocales;
};
export const translate = (key: string) => {
const currentLocale = getAppLocales()[0].languageCode;
return translations[currentLocale][key] || key;
};
```
--------------------------------
### generateBackgroundStyle(backgroundImageUri?, backgroundColor?, backgroundColorOverlay?)
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-helpers.md
Generates a background style. When no background URI, returns an object with backgroundColor and opacity based on overlay flag.
```APIDOC
## generateBackgroundStyle(backgroundImageUri?, backgroundColor?, backgroundColorOverlay?)
### Description
Generates a background style.
### Parameters
- **backgroundImageUri** (string) - Optional - The background image URI.
- **backgroundColor** (string) - Optional - The background color.
- **backgroundColorOverlay** (boolean) - Optional - Whether to apply an overlay.
### Returns
- **{ backgroundColor, opacity } | undefined** - When no background URI, returns `{ backgroundColor: backgroundColor || COLORS.WHITE, opacity: backgroundColorOverlay ? 0.7 : 1 }`.
```
--------------------------------
### Push KVATestData.json to device using vega exec vda push
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/README.md
Pushes the JSON search file to the device at the specified path. Use this after creating KVATestData.json to upload custom search data.
```bash
vega exec vda push KVATestData.json /home/app_user/packages/com.amazondeveloper.keplervideoapp/data
```
--------------------------------
### LiveForceSync component implementation
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/entry-points.md
Full-screen React component that ingests channel and program lineups on mount, showing a progress bar. Calls ingestChannelLineup and ingestProgramLineup from src/livetv/task/EpgSyncTask. On success waits 3000 ms then calls BackHandler.exitApp(); on failure sets failed=true and shows 'Channel Update Failed'. Channel ingestion maps to first 50% of progress, program ingestion to last 50%.
```tsx
const LiveForceSync = () => {
const [isInProgress, setIsInProgress] = useState(true);
const [progress, setProgress] = useState(0);
const [failed, setFailed] = useState(false);
const channelProgressCallback = (channelProgress: number) => {
setProgress(channelProgress * 50);
};
const programProgressCallback = (programProgress: number) => {
setProgress(50 + programProgress * 50);
};
...
};
export default LiveForceSync;
```
--------------------------------
### VideoHandler usage: preBufferVideo, setMediaData, destroyMediaPlayerSync
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Shows how to instantiate VideoHandler with refs and state setters, then pre-buffer, switch media, and clean up synchronously. Requires React state for player lifecycle events and a TitleData object.
```ts
import { VideoHandler } from './src/utils/VideoHandler';
import { VideoPlayer } from '@amazon-devices/react-native-w3cmedia';
import { ShakaPlayer } from './src/w3cmedia/shakaplayer/ShakaPlayer';
import { TitleData } from './src/types/TitleData';
const videoRef = React.useRef(null);
const playerRef = React.useRef(null);
const [isInit, setIsInit] = React.useState(false);
const [isEnded, setIsEnded] = React.useState(false);
const [isError, setIsError] = React.useState(false);
const [elapsedM, setElapsedM] = React.useState(0);
const [buffering, setBuffering] = React.useState(false);
const handler = new VideoHandler(
videoRef, playerRef, titleData,
setIsInit, setIsEnded, setIsError, setElapsedM, setBuffering,
);
// Pre-buffer and start playback
await handler.preBufferVideo(componentInstance);
// Switch to a new video
handler.setMediaData(otherTitleData);
handler.loadVideoElements();
// Clean up
const ok = handler.destroyMediaPlayerSync();
```
--------------------------------
### loadAdaptiveMediaPlayer()
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Loads adaptive media (HLS/DASH) using ShakaPlayer.
```APIDOC
## loadAdaptiveMediaPlayer()
### Description
Loads adaptive media (HLS/DASH) using ShakaPlayer.
### Return
void
```
--------------------------------
### loadStaticMediaPlayer(video: { src: string; autoplay: boolean; pause: () => void; load: () => void })
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/VideoHandler.md
Loads static media (MP4) into the video player.
```APIDOC
## loadStaticMediaPlayer(video: { src: string; autoplay: boolean; pause: () => void; load: () => void })
### Description
Loads static media (MP4) into the video player.
### Parameters
- **video** (object) - Required - The video object with src, autoplay, pause, and load properties.
### Return
void
```
--------------------------------
### generateColorOverlayStyle(backgroundImageUri?, backgroundColor?)
Source: https://github.com/amazonappdev/vega-video-sample/blob/main/_autodocs/api-reference/blocks-helpers.md
Generates a color overlay style. Returns an object with backgroundColor and opacity 0 when a background URI is provided, otherwise undefined.
```APIDOC
## generateColorOverlayStyle(backgroundImageUri?, backgroundColor?)
### Description
Generates a color overlay style.
### Parameters
- **backgroundImageUri** (string) - Optional - The background image URI.
- **backgroundColor** (string) - Optional - The background color.
### Returns
- **{ backgroundColor, opacity: 0 } | undefined** - When a background URI is provided, otherwise undefined.
```