### Samsung TV Billing API: JavaScript buyItem Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/billing-api
A JavaScript code example demonstrating how to use the `buyItem` method of the Samsung TV Billing API. It shows the setup of payment details and the calls to initiate a purchase.
```JavaScript
var strAppId = "";
var strUID = webapis.sso.getLoginUid();
var paymentDetails = new Object();
paymentDetails.OrderItemID="PID_2_consum_cupn";
paymentDetails.OrderTitle="hello consum US coupon";
paymentDetails.OrderTotal="2";
paymentDetails.OrderCurrencyID="USD";
paymentDetails.OrderCustomID=strUID;
var stringifyResult = JSON.stringify(paymentDetails);
var onsuccess = function(data) {};
var onerror = function(error) {};
webapis.billing.buyItem(strAppId, "DEV", stringifyResult, onsuccess, onerror);
```
--------------------------------
### Get AllShare Plugin Version Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/asfservice-api
Demonstrates how to call the getVersion method of the AllshareManager and handle potential errors.
```javascript
try {
var value = webapis.allshare.getVersion();
console.log("version value = " + value);
}
catch (error) {
console.log("error code = " + error.code);
}
```
--------------------------------
### Install Package
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Installs a package from a specified file URI. It supports progress and error callbacks for managing the installation process. Virtual paths must be converted to file URIs before use.
```javascript
var onInstallation = {
onprogress: function(packageId, percentage) {
console.log("On installation(" + packageId + ") : progress(" + percentage + ")");
},
oncomplete: function(packageId) {
console.log("Installation(" + packageId + ") Complete");
}
}
var onError = function (err) {
console.log("Error occurred on installation : " + err.name);
}
// Let's assume that the "test.wgt" file exists in the downloads directory
tizen.filesystem.resolve("downloads/test.wgt",
function (file) {
console.log("file URI : " + file.toURI());
tizen.package.install(file.toURI(), onInstallation, onError);
},
function (err) {
console.log("Error occurred on resolve : " + err.name);
},
"r");
```
--------------------------------
### Get ServiceProvider Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/asfservice-api
Shows how to retrieve a ServiceProvider object connected to the AllShare Framework. It includes error handling for cases where the service provider might not be created properly.
```javascript
try {
// You must already have a ServiceProvider object
var serviceProvider = webapis.allshare.serviceconnector.getServiceProvider();
if (serviceProvider == null) {
console.log("Service provider was not created properly");
}
}
catch(e) {
console.log(e.message);
}
```
--------------------------------
### listFiles Example
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/filesystem-api
Example demonstrating how to use the listFiles method to list the contents of a directory.
```APIDOC
### listFiles Example
#### Code Example
```javascript
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
/* Alerts each name of dir's content. */
console.log(files[i].name);
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
/* List directory content. */
dir.listFiles(onsuccess, onerror);
```
```
--------------------------------
### JavaScript Example for onchange Callback
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/productinfo-api
A JavaScript example demonstrating how to implement the onchange callback function for product info configuration changes. It logs the changed key to the console.
```JavaScript
var onchange = function (key){
console.log(" changed key is = " + key);
}
```
--------------------------------
### Install Package
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Installs a package from a specified file URI on the device. It provides progress and error callbacks.
```APIDOC
## POST /package/install
### Description
Installs a package with a specified file on a device. This API notifies the progress and completion of an installation request.
### Method
POST
### Endpoint
/package/install
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **packageFileURI** (DOMString) - Required - The location of the package to install.
- **progressCallback** (PackageProgressCallback) - Required - The method to invoke when the installation is in progress or has been completed.
- **errorCallback** (optional ErrorCallback) - Optional - The method to invoke when an error occurs.
### Request Example
```javascript
var onInstallation = {
onprogress: function(packageId, percentage) {
console.log("On installation(" + packageId + ") : progress(" + percentage + ")");
},
oncomplete: function(packageId) {
console.log("Installation(" + packageId + ") Complete");
}
}
var onError = function (err) {
console.log("Error occurred on installation : " + err.name);
}
tizen.filesystem.resolve("downloads/test.wgt",
function (file) {
tizen.package.install(file.toURI(), onInstallation, onError);
},
function (err) {
console.log("Error occurred on resolve : " + err.name);
},
"r");
```
### Response
#### Success Response (200)
Indicates successful initiation of the installation.
#### Response Example
```json
{
"status": "Installation initiated"
}
```
### Errors
- **NotFoundError**: If the package is not found at the specified location.
- **UnknownError**: If the platform disallows installation or another platform error occurs.
- **TypeMismatchError**: If any input parameter is not compatible with the expected type.
- **SecurityError**: If the application lacks the necessary privilege.
```
--------------------------------
### Install Package
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Installs a package on the device. It takes the URI of the package file, a callback for progress updates, and an optional error callback.
```APIDOC
## POST /package/install
### Description
Installs a package on the device.
### Method
POST
### Endpoint
/package/install
### Parameters
#### Request Body
- **packageFileURI** (DOMString) - Required - The URI of the package file to install.
- **progressCallback** (PackageProgressCallback) - Required - A callback function to receive installation progress updates.
- **errorCallback** (ErrorCallback) - Optional - A callback function to handle errors during installation.
### Response
#### Success Response (200)
Indicates successful initiation of the installation process. The actual progress and completion will be reported via the `progressCallback`.
#### Response Example
(No specific JSON response body is defined for success, as progress is handled via callbacks.)
### Errors
- **WebAPIException**: Thrown if an error occurs during the operation. The specific error code and message will be provided.
```
--------------------------------
### Get SystemInfo Version
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/systeminfo-api
This code example demonstrates how to retrieve the version information of the SystemInfo plugin using the getVersion() method. It includes error handling for potential issues during the API call.
```javascript
try {
var version = webapis.systeminfo.getVersion();
console.log("Version = " + version);
} catch(error) {
console.log("error code = " + error.code);
}
```
--------------------------------
### Retrieve Playlist Items using get (JavaScript)
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/content-api
This example demonstrates how to retrieve all playlist items from a specific playlist using the 'get' method. It first fetches all available playlists and then calls 'get' on the first playlist to retrieve its items, logging their names. Error handling for playlist retrieval and item retrieval is included.
```javascript
var gPlaylists, gItems, gCurPlaylist;
function getSuccess(items) {
gItems = items;
console.log("Playlist items:");
for(var i = 0; i < items.length ; ++i) {
console.log("[" + i + "]: name:" + items[i].name);
}
}
function getFail(err) {
console.log("get items failed: " + err);
}
function getPlaylistsFail(err) {
console.log("getPlaylists failed: " + err);
}
function getPlaylistsSuccess(playlists) {
gPlaylists = playlists;
if(gPlaylists.length === 0) {
console.log("Please create at least 1 playlist!");
return;
}
gCurPlaylist = gPlaylists[0];
// To retrieves all playlist items of 'gCurPlaylist' playlist.
gCurPlaylist.get(getSuccess, getFail);
}
tizen.content.getPlaylists(getPlaylistsSuccess, getPlaylistsFail);
```
--------------------------------
### Get DeviceFinder Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/asfservice-api
Illustrates how to obtain a DeviceFinder object from a ServiceProvider to find AllShare devices. Includes basic error handling.
```javascript
var serviceProvider = webapis.allshare.serviceconnector.getServiceProvider();
try {
deviceFinder = serviceProvider.getDeviceFinder();
} catch(e) {
console.log(e.name);
}
```
--------------------------------
### Get ServiceState Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/asfservice-api
Demonstrates how to retrieve the current ASF service state using the getServiceState method. Includes error handling for potential issues during retrieval.
```javascript
// You must already have a ServiceProvider object
var serviceProvider;
try {
serviceState = serviceProvider.getServiceState();
} catch(e) {
console.log(e.name);
}
```
--------------------------------
### Get Installed Packages Info
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Retrieves information about all installed packages on the device.
```APIDOC
## GET /packages/info
### Description
Gets information of the installed packages. The result contains snapshots of the installed packages' information.
### Method
GET
### Endpoint
/packages/info
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
var onSuccess = function(packages) {
console.log("Installed packages:");
for (var i = 0; i < packages.length; i++) {
console.log(" ID: " + packages[i].packageId + ", Name: " + packages[i].name);
}
};
var onError = function(err) {
console.log("Error occurred: " + err.name);
};
tizen.package.getPackagesInfo(onSuccess, onError);
```
### Response
#### Success Response (200)
- **packages** (PackageInformationArray) - An array of installed package information objects.
#### Response Example
```json
[
{
"packageId": "org.example.app1",
"name": "Example App 1",
"version": "1.0.0",
"author": "Example Corp",
"description": "A sample application.",
"iconPath": "/path/to/icon.png",
"installedTime": "2023-10-27T10:00:00Z"
},
{
"packageId": "org.example.app2",
"name": "Example App 2",
"version": "2.5.1",
"author": "Example Corp",
"description": "Another sample application.",
"iconPath": "/path/to/icon2.png",
"installedTime": "2023-10-26T15:30:00Z"
}
]
```
### Errors
- **UnknownError**: If any other platform error occurs.
- **TypeMismatchError**: If any input parameter is not compatible with the expected type.
```
--------------------------------
### Get Installed Applications and Log IDs in JavaScript
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
Retrieves a list of installed applications using tizen.application.getAppsInfo and logs the ID of each application to the console.
```JavaScript
function onListInstalledApps(applications) {
for (var i = 0; i < applications.length; i++)
console.log("ID : " + applications[i].id);
}
tizen.application.getAppsInfo(onListInstalledApps);
```
--------------------------------
### Get Installed Applications Information
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
Retrieves a list of information for all applications installed on the device. The data reflects the application state at the time of the request.
```APIDOC
## GET /apps/info
### Description
Gets the list of installed applications' information on a device. The information contained on each application corresponds to the application state at the time when the list had been generated.
### Method
GET
### Endpoint
/apps/info
### Parameters
#### Query Parameters
- **successCallback** (function) - Required - The method to call when the invocation ends successfully.
- **errorCallback** (function) - Optional - The method to call when an error occurs.
### Response
#### Success Response (200)
- **applications** (array) - An array of ApplicationInformation objects.
### Response Example
```json
{
"applications": [
{
"id": "com.example.app1",
"version": "1.0.0",
"appName": "Example App 1",
"installTime": "2023-01-01T10:00:00Z"
},
{
"id": "com.example.app2",
"version": "2.0.1",
"appName": "Example App 2",
"installTime": "2023-02-15T14:30:00Z"
}
]
}
```
### Errors
- **UnknownError**: If an unknown error occurs.
- **TypeMismatchError**: If any input parameter is not compatible with the expected type.
```
--------------------------------
### Add Application Information Event Listener (JavaScript)
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
Installs a callback triggered by changes in installed applications (install, uninstall, update). It returns a listener ID and starts detection asynchronously. The listener remains active until explicitly removed.
```javascript
var appEventCallback = {
oninstalled: function(appInfo) {
console.log('The application ' + appInfo.name + ' is installed');
},
onupdated: function(appInfo) {
console.log('The application ' + appInfo.name + ' is updated');
},
onuninstalled: function(appid) {
console.log('The application ' + appid + ' is uninstalled');
}
};
var watchId = tizen.application.addAppInfoEventListener(appEventCallback);
```
--------------------------------
### Playlist Management Example (JavaScript)
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/content-api
Demonstrates a workflow for retrieving playlists, displaying items, removing an item, and then re-fetching items to verify the removal. Includes success and failure logging for asynchronous operations.
```JavaScript
var gPlaylists, gItems, gCurPlaylist;
function get2Fail(err) {
console.log("get items (after remove) failed: " + err);
}
function get2Success(items) {
console.log("Playlist items:");
for(var i = 0; i < items.length ; ++i) {
console.log("[" + i + "]: name:" + items[i].content.name);
}
}
function getSuccess(items) {
gItems = items;
if(gItems.length < 1) {
console.log("Please add at least 1 tracks to playlist!");
return;
}
console.log("Original playlist:");
for(var i = 0; i < gItems.length ; ++i) {
console.log("[" + i + "]: name:" + gItems[i].content.name);
}
console.log("Will remove item at index [0] name:" + gItems[0].content.name);
gCurPlaylist.remove(gItems[0]);
gCurPlaylist.get(get2Success, get2Fail);
}
function getFail(err) {
console.log("get items failed: " + err);
}
function getPlaylistsFail(err) {
console.log("getPlaylists failed: " + err);
}
function getPlaylistsSuccess(playlists) {
gPlaylists = playlists;
if(gPlaylists.length === 0) {
console.log("Please create at least 1 playlist!");
return;
}
gCurPlaylist = gPlaylists[0];
gCurPlaylist.get(getSuccess, getFail);
}
tizen.content.getPlaylists(getPlaylistsSuccess, getPlaylistsFail);
```
--------------------------------
### Get Installed Apps Info (JavaScript)
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
Fetches information about all installed applications on the device. The success callback is invoked with an array of ApplicationInformation objects. An optional error callback can be provided to handle errors.
```javascript
function onListInstalledApps(applications) {
for (var i = 0; i < applications.length; i++)
console.log("ID : " + applications[i].id);
}
tizen.application.getAppsInfo(onListInstalledApps);
```
--------------------------------
### Get Installed Packages Information
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Retrieves information about all installed packages on the device. A success callback receives an array of package information, and an optional error callback handles potential platform errors.
```javascript
tizen.package.getPackagesInfo(
function(packageInfoArray) {
console.log("Number of installed packages: " + packageInfoArray.length);
for (var i = 0; i < packageInfoArray.length; i++) {
console.log("Package ID: " + packageInfoArray[i].packageId + ", Name: " + packageInfoArray[i].name);
}
},
function(err) {
console.log("Error occurred: " + err.name);
}
);
```
--------------------------------
### File System Operations - Example
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/filesystem-api
Demonstrates how to resolve a directory, list files, create a new file, and write content to it with specified encoding.
```APIDOC
## POST /filesystem/resolve
### Description
Resolves a directory and performs operations like listing files and creating new files.
### Method
POST (Implicit, as this is a client-side JavaScript example interacting with the Tizen API)
### Endpoint
N/A (Client-side Tizen API)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None (Direct JavaScript function calls)
### Request Example
```javascript
var documentsDir;
function onsuccess(files) {
for (var i = 0; i < files.length; i++) {
console.log("File Name is " + files[i].name); /* Displays file name. */
}
var testFile = documentsDir.createFile("test.txt");
if (testFile != null) {
testFile.openStream("w",
function(fs) {
fs.write("HelloWorld");
fs.close();
},
function(e) {
console.log("Error " + e.message);
},
"UTF-8");
}
}
function onerror(error) {
console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir) {
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e) {
console.log("Error " + e.message);
},
"rw");
```
### Response
#### Success Response (200)
File operations are performed asynchronously via callbacks.
#### Response Example
Console logs indicating file operations and success/error messages.
```
--------------------------------
### AlarmAbsolute getNextScheduledDate Method Example
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/alarm-api
Demonstrates the usage of the `getNextScheduledDate` method of the `AlarmAbsolute` interface. This example shows how to retrieve the next scheduled time for an alarm and log it to the console. It also includes the initial setup for creating and adding an alarm.
```javascript
// Gets the current application ID.
var appId = tizen.application.getCurrentApplication().appInfo.id;
// Sets an alarm on January 1st 2014 08:00
var date = new Date(2014, 0, 1, 8, 0);
var alarm1 = new tizen.AlarmAbsolute(date);
tizen.alarm.add(alarm1, appId);
var date = alarm1.getNextScheduledDate();
console.log("next scheduled time is " + date);
```
--------------------------------
### MediaProvider Success Callback and Search Example using JavaScript
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/asfservice-api
Defines a callback for successful media provider retrieval operations and provides an example of searching for media items. It utilizes a success callback to process the retrieved items and an error callback for handling potential issues during the search. This requires the 'allshare' privilege.
```javascript
//onsuccess searchCB
var serviceProvider = webapis.allshare.serviceconnector.getServiceProvider();
var keyword = "foo";
// Define a browse callback
function searchCB(list, endOfItem, providerId){
// Retrieve the item list
}
function errorCB(error, device){
console.log(device + " raises " + error);
}
// Define a filter to browse videos only
var filter = new webapis.AttributeFilter("itemType", null, {"VIDEO"});
try {
var providers = serviceProvider.getDeviceFinder().getDeviceList("MEDIAPROVIDER");
if (providers.length > 0) {
// Search for the keyword in the first DMS
providers[0].search(keyword, 0, 40, searchCB, errorCB, filter);
}
} catch(e) {
console.log(e.message);
}
```
--------------------------------
### Get Caption Value Example
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/tvinfo-api
Demonstrates how to retrieve the current value of a caption setting using the getCaptionValue method.
```javascript
console.log("Caption menu turned on: " + (tizen.tvinfo.getCaptionValue("CAPTION_ONOFF_KEY") === "CAPTION_ON"));
```
--------------------------------
### Samsung Smart TV WebAPI Overview
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/webapi-api
Provides an overview of the Samsung Smart TV WebAPI, including the script to include and the main namespace.
```APIDOC
## Samsung Smart TV WebAPI
> To use Samsung Product API, include the following script in your index.html:
> ```html
```
The module defines the functionalities provided as the Samsung TV for Tizen Platform Product API. This API specifies the location in the ECMAScript hierarchy where the Samsung TV for Tizen Platform Product API is instantiated (window.webapis).
**Since**: 2.3
**Product**: TV, AV, B2B
## Summary of Interfaces and Methods
| Interface | Method |
|----------------|------------------|
| WebApiObject | |
| WebApi | |
| WebAPIException| |
| WebAPIError | |
| SuccessCallback| void onsuccess();|
| ErrorCallback | void onerror(WebAPIError error);|
```
--------------------------------
### AVPlayStore API Overview
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/avplaystore-api
This section provides an overview of the AVPlayStore API, including its purpose, supported products, and a summary of its interfaces and methods.
```APIDOC
## AVPlayStore API
> To use Samsung Product API:
```html
```
This module defines the multimedia player functionalities provided by the Tizen Samsung Product API.
**Since**: 2.3
**Product**: TV, AV, B2B
## Summary of Interfaces and Methods
Interface | Method
---|---
AVPlayStoreManagerObject |
AVPlayStoreManager | AVPlayManagerObject getPlayer();
```
--------------------------------
### Status Event Callback API
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
The StatusEventCallback interface specifies a callback for getting notified when the status of an installed application has changed. This includes activation and deactivation.
```APIDOC
## StatusEventCallback
### Description
Specifies a callback for getting notified when the status of the installed application has been changed.
### Methods
#### onchange
Called when the status event occurs.
* **Parameters**
* `appId` (ApplicationId) - Id of the application that status has been changed.
* `isActive` (boolean) - The new status of the application.
### Note
Example of using can be find at addAppStatusChangeListener code example.
```
--------------------------------
### Get All Packages Information
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
Retrieves information for all installed packages on the device. It requires a success callback to receive the array of package information and an optional error callback.
```APIDOC
## GET /packages/info
### Description
Retrieves information for all installed packages on the device.
### Method
GET
### Endpoint
/packages/info
### Parameters
#### Query Parameters
- **successCallback** (PackageInformationArraySuccessCallback) - Required - A callback function that receives an array of PackageInformation objects.
- **errorCallback** (ErrorCallback) - Optional - A callback function to handle errors during the retrieval process.
### Response
#### Success Response (200)
- **informationArray** (PackageInformation[]) - An array of package information objects.
#### Response Example
```json
{
"informationArray": [
{
"id": "com.example.app1",
"name": "Example App 1",
"iconPath": "/usr/share/icons/app1.png",
"version": "1.0.0",
"totalSize": 1024000,
"dataSize": 512000,
"lastModified": "2023-10-27T10:00:00Z",
"author": "Example Corp",
"description": "This is the first example app.",
"appIds": ["app1_instance1"]
},
{
"id": "com.example.app2",
"name": "Example App 2",
"iconPath": "/usr/share/icons/app2.png",
"version": "2.1.0",
"totalSize": 2048000,
"dataSize": 1024000,
"lastModified": "2023-10-26T15:30:00Z",
"author": "Another Corp",
"description": "This is the second example app.",
"appIds": ["app2_instance1", "app2_instance2"]
}
]
}
```
### Errors
- **WebAPIException**: Thrown if an error occurs during the operation. The specific error code and message will be provided.
```
--------------------------------
### Object Detection API Usage Example (JavaScript)
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/objectdetection-api
Demonstrates the usage of the Samsung SmartTV Object Detection API in JavaScript. It covers creating, initializing, running detection on an image, deinitializing, and destroying the object detection instance. Error handling is included.
```javascript
try {
let handle = webapis.objectdetection.create();
webapis.objectdetection.init(handle, "FACE");
webapis.objectdetection.run(handle, "/opt/media/USBDriveA1/images/face.png");
webapis.objectdetection.deinit(handle);
webapis.objectdetection.destroy(handle);
} catch (e) {
console.error("error code = " + error.code + ", error name = " + error.name + ", error message = " + error.message);
}
```
--------------------------------
### GET /products
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/billing-api
Retrieves a paginated list of products registered on the Billing (DPI) server.
```APIDOC
## GET /products
### Description
Retrieves the list of products registered on the Billing (DPI) server.
### Method
GET
### Endpoint
`/products`
### Parameters
#### Query Parameters
- **appId** (DOMString) - Required - Application ID
- **countryCode** (DOMString) - Required - TV country code
- **pageSize** (DOMString) - Optional - Number of products retrieved per page (maximum 100)
- **pageNumber** (DOMString) - Optional - Requested page number (1 ~ N)
- **checkValue** (DOMString) - Required - Security check value. Generated by HMAC SHA256 on concatenated parameters (`appId` + `countryCode`) using a DPI security key, then Base64 encoded.
- **serverType** (TVServerType) - Required - Billing server type (e.g., "DEV", "STAGING", "PRODUCTION")
#### Request Example
```javascript
var strSecurityKey = ""; // DPI security key from DPI portal
var strAppId = "";
var strCountryCode = webapis.productinfo.getSystemConfig(webapis.productinfo.ProductInfoConfigKey.CONFIG_KEY_SERVICE_COUNTRY);
var reqParams = strAppId + strCountryCode;
var hash = CryptoJS.HmacSHA256(reqParams, strSecurityKey);
var strCheckValue = CryptoJS.enc.Base64.stringify(hash);
webapis.billing.getProductsList(strAppId, strCountryCode, "100", "1", strCheckValue, "DEV",
function(data) { console.log(data); },
function(error) { console.error(error); }
);
```
### Response
#### Success Response (200)
- **apiResult** (object) - Contains the product list and status information.
- **CPStatus** (string) - "100000" indicates successful server communication and valid data.
- **productList** (array) - List of product objects.
#### Response Example
```json
{
"CPStatus": "100000",
"productList": [
{
"productId": "prod123",
"title": "Premium Content",
"description": "Access to exclusive content.",
"price": "$9.99"
}
]
}
```
### Exceptions
- **WebAPIException**
- **TypeMismatchError**: If any input parameter has an incompatible type.
- **InvalidValuesError**: If `serverType` contains an invalid value.
- **SecurityError**: If the application lacks the necessary privilege.
```
--------------------------------
### Project Setup with create-tizen-app
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-typescript-api-references
The `create-tizen-app` package is a wizard tool to easily configure and create Tizen web applications, supporting both CommonJS and TypeScript development with various bundlers and editor extensions.
```APIDOC
## Setting up Project with create-tizen-app
### Description
A wizard tool to easily configure and create Tizen web applications, supporting CommonJS or TypeScript, Webpack or Parcel, and editor extensions.
### Usage
Run the following command to start the wizard:
```bash
npx create-tizen-app
```
### Options
- Language: TypeScript / CommonJS
- Bundler: Webpack / Parcel
- Editor Extension: VSCode tizentv / Atom tizentv
- WITs (Web Inspector Tools)
```
--------------------------------
### Get Package Information with Tizen API
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/package-api
This JavaScript code snippet shows how to get information about a specific installed package using the Tizen API. The `tizen.package.getPackageInfo` method can be called with a package ID or `null` to retrieve information for the current application. It returns a `PackageInformation` object containing details like ID, name, version, and size.
```javascript
var packageInfo = tizen.package.getPackageInfo(null);
console.log("Current Package ID : " + packageInfo.id);
```
--------------------------------
### SystemInfo API Overview
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/systeminfo-api
Provides an overview of the SystemInfo API, detailing the types of system properties accessible and how to check for property availability.
```APIDOC
## SystemInfo API
### Description
This specification defines interfaces and methods that provide web applications with access to various properties of a system. This API also provides interfaces and methods that can retrieve statuses of hardware devices, get the value of selected properties, and subscribe to asynchronous notifications of changes for selected values.
Web applications can use this API to access the following system properties:
* BATTERY
* BUILD
* CAMERA_FLASH (**Since** : 2.4)
* CELLULAR_NETWORK
* CPU
* DEVICE_ORIENTATION
* DISPLAY
* ETHERNET_NETWORK (**Since** : 2.4)
* LOCALE (**Since** : 2.1)
* MEMORY (**Since** : 2.3)
* NETWORK
* NET_PROXY_NETWORK (**Since** : 3.0)
* PERIPHERAL (**Since** : 2.1)
* SIM
* STORAGE
* VIDEOSOURCE (**Since** : 2.3)
* WIFI_NETWORK
* ADS (**Since** : 3.0)
* PANEL(**Since** : 5.5)
* SOURCE_INFO(**Since** : 5.5)
* SERVICE_COUNTRY(**Since** : 5.5)
Not all above properties may be available on every Tizen device. For instance, a device may not support the telephony feature. In that case, CELLULAR_NETWORK and SIM are not available.
To check the available SystemInfoPropertyId, getCapability() method can be used.
### Capability Checking Examples
* **BATTERY**: `tizen.systeminfo.getCapability("http://tizen.org/feature/battery")`
* **CAMERA_FLASH**: `tizen.systeminfo.getCapability("http://tizen.org/feature/camera.back.flash")`
* **CELLULAR_NETWORK**: `tizen.systeminfo.getCapability("http://tizen.org/feature/network.telephony")`
* **DISPLAY**: `tizen.systeminfo.getCapability("http://tizen.org/feature/screen")`
* **ETHERNET_NETWORK**: `tizen.systeminfo.getCapability("http://tizen.org/feature/network.ethernet")`
* **NET_PROXY_NETWORK**: `tizen.systeminfo.getCapability("http://tizen.org/feature/network.net_proxy")`
* **SIM**: `tizen.systeminfo.getCapability("http://tizen.org/feature/network.telephony")`
* **WIFI_NETWORK**: `tizen.systeminfo.getCapability("http://tizen.feature/network.wifi")`
For more information on the SystemInfo features, see System Information Guide.
**Since**: 1.0
```
--------------------------------
### Pose Estimation - Run
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/poseestimation-api
Runs pose estimation on an image from a given URL to retrieve keypoint information. Requires an initialized pose estimation handle.
```APIDOC
## POST /poseestimation/run
### Description
Runs pose estimation with a content URL to get the keypoint information from it.
### Method
POST
### Endpoint
/poseestimation/run
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **handle** (PoseEstimationHandle) - Required - Handle of pose estimation.
- **url** (DOMString) - Required - Content URL. It should be an absolute local path of a PNG image.
- **roi** (Array) - Required - The body ROI information of the input image. roi[0] = x coordinate, roi[1] = y coordinate, roi[2] = width, roi[3] = height. Values should be between 0 and 1.
### Request Example
```json
{
"handle": "pose_estimation_handle_123",
"url": "/opt/media/images/sample.png",
"roi": [0.25, 0.25, 0.5, 0.5]
}
```
### Response
#### Success Response (200)
- **PoseEstimationKeypoints[]** (Array) - An array containing all detected keypoints, each with 'keypoint', 'confidence', 'x', and 'y' properties.
#### Response Example
```json
[
{
"keypoint": "nose",
"confidence": 0.95,
"x": 100,
"y": 120
},
{
"keypoint": "left_eye",
"confidence": 0.92,
"x": 90,
"y": 110
}
]
```
### Exceptions
- **WebAPIException**
- **NotSupportedError**: If the product does not support pose estimation.
- **TypeMismatchError**: If parameter types are incorrect.
- **InvalidValuesError**: If any input parameter contains an invalid value.
- **UnknownError**: For any other errors.
```
--------------------------------
### Set Streaming Property - Smooth Streaming Example
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/avplay-api
Demonstrates setting adaptive streaming information for Smooth Streaming, including bitrate and start bitrate configurations.
```javascript
var BitRateString = "BITRATES=5000~10000|STARTBITRATE=HIGHEST|SKIPBITRATE=LOWEST";
webapis.avplay.setStreamingProperty("ADAPTIVE_INFO", BitRateString);
```
--------------------------------
### AVPlay API Overview
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/avplay-api
Provides information on how to use the Samsung Product API and includes a script for loading the webapis library. It also details the AVPlay module's purpose, version, and supported products.
```APIDOC
## AVPlay API
### Description
This module defines the multimedia player functionalities provided by the Tizen Samsung TV Product API.
### Product
TV, AV, B2B
### Since
2.3
### Usage
To use Samsung Product API, include the following script in your index.html:
```html
```
### Color Theme
Should be loaded in index.html.
```
--------------------------------
### ApplicationManager Interface Definition
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/application-api
Defines the ApplicationManager interface, which offers methods to retrieve application information, install applications, kill applications by context ID, find applications by control, get application contexts, get application information, certificates, shared URIs, and metadata. It also includes methods for battery and app usage information, and managing status change listeners.
```webidl
interface ApplicationManager {
Application getCurrentApplication() raises(WebAPIException);
void kill(ApplicationContextId contextId,
optional SuccessCallback? successCallback,
optional ErrorCallback? errorCallback) raises(WebAPIException);
void findAppControl(ApplicationControl appControl,
FindAppControlSuccessCallback successCallback,
optional ErrorCallback? errorCallback) raises(WebAPIException);
void getAppsContext(ApplicationContextArraySuccessCallback successCallback,
optional ErrorCallback? errorCallback) raises(WebAPIException);
ApplicationContext getAppContext(optional ApplicationContextId? contextId) raises(WebAPIException);
void getAppsInfo(ApplicationInformationArraySuccessCallback successCallback,
optional ErrorCallback? errorCallback) raises(WebAPIException);
ApplicationInformation getAppInfo(optional ApplicationId? id) raises(WebAPIException);
ApplicationCertificate[] getAppCerts(optional ApplicationId? id) raises(WebAPIException);
DOMString getAppSharedURI(optional ApplicationId? id) raises(WebAPIException);
ApplicationMetaData[] getAppMetaData(optional ApplicationId? id) raises(WebAPIException);
void getBatteryUsageInfo(BatteryUsageInfoArraySuccessCallback successCallback,
optional ErrorCallback? errorCallback,
optional long? days,
optional long? limit) raises(WebAPIException);
void getAppsUsageInfo(AppsUsageInfoArraySuccessCallback successCallback,
optional ErrorCallback? errorCallback,
optional ApplicationUsageMode? mode,
optional ApplicationUsageFilter? filter,
optional long? limit) raises(WebAPIException);
long addAppStatusChangeListener(StatusEventCallback eventCallback, optional ApplicationId? appId) raises(WebAPIException);
void removeAppStatusChangeListener(long watchId) raises(WebAPIException);
};
```
--------------------------------
### Download API Feature Keys
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/systeminfo-api/getting-device-capabilities-using-systeminfo-api
Provides information on keys for checking Download API support and network requirements (telephony, Wi-Fi).
```APIDOC
## Download API Feature Keys
### Description
This section lists the keys to verify if the Download API is supported on a Tizen device, including checks for telephony and Wi-Fi network support.
### Method
GET
### Endpoint
`/sys/info`
### Parameters
#### Query Parameters
- **key** (string) - Required - One of the following: `http://tizen.org/feature/download`, `http://tizen.org/feature/network.telephony`, `http://tizen.org/feature/network.wifi`
### Response
#### Success Response (200)
- **value** (boolean) - Returns `true` if the specified download or network feature is supported; otherwise, `false`.
### Request Example
```
GET /sys/info?key=http://tizen.feature/network.wifi
```
### Response Example
```json
{
"value": true
}
```
```
--------------------------------
### Get AppCommon API Version
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/appcommon-api
This example demonstrates how to retrieve the version of the AppCommon API plugin. It includes error handling to catch potential issues during the API call. Requires the webapis.js file to be included.
```javascript
try {
var value = webapis.appcommon.getVersion();
console.log(" version value = " + value);
} catch (error) {
console.log(" error code = " + error.code);
}
```
--------------------------------
### Pose Estimation - Run with Buffer
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/poseestimation-api
Runs pose estimation on a base64 encoded image buffer to retrieve keypoint information. Requires an initialized pose estimation handle.
```APIDOC
## POST /poseestimation/runWithBuffer
### Description
Runs pose estimation with a base64 encoded buffer to get the keypoint information from it.
### Method
POST
### Endpoint
/poseestimation/runWithBuffer
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **handle** (PoseEstimationHandle) - Required - Handle of pose estimation.
- **buffer** (DOMString) - Required - Base64 encoded buffer data of a PNG image file.
- **roi** (Array) - Required - The body ROI information of the input image. roi[0] = x coordinate, roi[1] = y coordinate, roi[2] = width, roi[3] = height. Values should be between 0 and 1.
### Request Example
```json
{
"handle": "pose_estimation_handle_123",
"buffer": "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPU...",
"roi": [0.25, 0.25, 0.5, 0.5]
}
```
### Response
#### Success Response (200)
- **PoseEstimationKeypoints[]** (Array) - An array containing all detected keypoints, each with 'keypoint', 'confidence', 'x', and 'y' properties.
#### Response Example
```json
[
{
"keypoint": "right_shoulder",
"confidence": 0.88,
"x": 200,
"y": 150
},
{
"keypoint": "left_shoulder",
"confidence": 0.85,
"x": 100,
"y": 150
}
]
```
### Exceptions
- **WebAPIException**
- **NotSupportedError**: If the product does not support pose estimation.
- **TypeMismatchError**: If parameter types are incorrect.
- **InvalidValuesError**: If any input parameter contains an invalid value.
- **UnknownError**: For any other errors.
```
--------------------------------
### Get Product Model Code - JavaScript
Source: https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/productinfo-api
Retrieves the model code of the product, for example, "15_HAWKP". This function requires the productinfo privilege and may result in a SecurityError if the privilege is insufficient. The model code is returned as a DOMString.
```javascript
try {
var value = webapis.productinfo.getModelCode();
console.log(" ModelCode value = " + value);
} catch (error) {
console.log(" error code = " + error.code);
}
```
--------------------------------
### Create Directory API
Source: https://developer.samsung.com/smarttv/develop/api-references/tizen-web-device-api-references/filesystem-api
Creates a new directory at the specified path. Optionally creates parent directories if they do not exist.
```APIDOC
## POST /filesystem/createDirectory
### Description
Creates a directory at the specified path. If `makeParents` is true, it will create any necessary parent directories.
### Method
POST
### Endpoint
/filesystem/createDirectory
### Parameters
#### Path Parameters
- **path** (string) - Required - The path of the directory to create.
#### Query Parameters
- **makeParents** (boolean) - Optional - Flag to create parent directories if they don't exist. Defaults to true.
#### Request Body
None
### Request Example
```javascript
tizen.filesystem.createDirectory("documents/foo_dir/bar_dir", true, successCallback, errorCallback);
```
### Response
#### Success Response (200)
- **path** (string) - The path of the created directory.
#### Response Example
```json
{
"path": "documents/foo_dir/bar_dir"
}
```
### Exceptions
- **WebAPIException**
- **InvalidValuesError**: If the path is invalid.
- **SecurityError**: If the application lacks necessary privileges.
- **TypeMismatchError**: If parameter types are incorrect.
```
--------------------------------
### Get Smart Hub Configuration - C#
Source: https://developer.samsung.com/smarttv/develop/api-references/tizenfx-tv-api-references/tizen.tv/environment-class
Retrieves the Smart Hub configuration, specifically the country code. Accessing this property requires the 'http://developer.samsung.com/privilege/productinfo' privilege, declared as Public. It is available starting from SDK version 4.4.0.
```csharp
string country = Environment.SmartHubConfig.Country;
```
--------------------------------
### Tizen Sockets Extension API Overview
Source: https://developer.samsung.com/smarttv/develop/api-references/webassembly-api-references/tizen-sockets-extension-api-references
This section provides an overview of the Tizen Sockets Extension API, highlighting its POSIX compliance, key differences, and supported extensions.
```APIDOC
## Tizen Sockets Extension API
### Description
The Tizen Sockets Extension API offers socket programming functionalities, largely adhering to the POSIX.1-2017 standard. However, there are notable differences when used in Emscripten or a web environment, including the lack of signals support, restrictions on calling socket functions from the main thread, and limitations on descriptor types accepted by functions like `poll()` and `select()`.
### Key Features and Differences
* **POSIX.1-2017 Conformance**: Most functions follow the POSIX.1-2017 standard.
* **Web Environment Differences**:
* No signals support.
* Socket functions cannot be called from the main thread without specific Emscripten flags (`-s PROXY_TO_PTHREAD` or `--proxy-to-worker`).
* Functions accepting multiple descriptors (e.g., `poll()`, `select()`) only accept one descriptor type at a time (either socket or file descriptors).
* `select()` may be slow; `poll()` is recommended.
* **Supported Extensions**:
* `SOCK_NONBLOCK` and `SOCK_CLOEXEC` flags for `socket()`.
* `accept4()` method.
* IPv4 multicast options for `getsockopt()` and `setsockopt()`.
* `gethostbyaddr()` and `gethostbyname()` methods.
### Required Privilege
* The `http://tizen.org/privilege/internet` privilege is required for using this extension. This privilege should be declared in the `config.xml` file.
```