### Install with NPM
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript-browserless
Install the piano-analytics-js NPM package using npm.
```bash
npm install piano-analytics-js --save
```
--------------------------------
### Shell Example
Source: https://developers.piano.io/analytics/data-api/getting-started/authentication
Example of how to authenticate a `curl` request using the `x-api-key` header.
```shell
curl "https://api.atinternet.io/v3/data/getData" \
-H "x-api-key: YOURAPIKEY"
```
--------------------------------
### Install with Yarn
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript-browserless
Install the piano-analytics-js package using Yarn.
```bash
yarn add piano-analytics-js
```
--------------------------------
### Ruby SDK Example
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/collection-api
Example of how to send events using a Ruby function.
```APIDOC
```ruby
begin
send_piano_analytics_event(
[
{
'name' => 'page.display',
'data' => {
'page' => 'Homepage',
'page_chapter1' => 'Main'
}
}
],
'123456789',
'9e8d6d5f-143a-4a21-a7d5-7348b56e130d',
'your.collection.domain'
)
rescue => e
puts "Failed to send events: #{e.message}"
# Implement retry logic or fallback here
end
```
```
--------------------------------
### Example SDK Configuration
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript
An example demonstrating how to set specific SDK configurations like `cookieDomain` and `path` before loading the Piano Analytics script.
```javascript
window._pac = window._pac || {};
_pac.cookieDomain = ".mysite.com";
_pac.path = "event";
;
```
--------------------------------
### Python Example
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/collection-api
Example of how to send events using the Collection API in Python.
```python
import requests
import json
import logging
def send_piano_analytics_event(events, site_id, visitor_id, collection_domain):
endpoint = f"https://{collection_domain}/event"
params = {
's': site_id,
'idclient': visitor_id
}
payload = {'events': events}
try:
response = requests.post(
endpoint,
params=params,
headers={'Content-Type': 'text/plain'},
data=json.dumps(payload),
timeout=30
)
response.raise_for_status()
logging.info("Events sent successfully")
return response.text
except requests.exceptions.RequestException as e:
logging.error(f"Failed to send events: {e}")
# Implement retry logic or fallback here
raise
```
--------------------------------
### Bash Script Example
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/collection-api
Example of how to send events using a bash script with curl.
```APIDOC
```bash
#!/bin/bash
# Function to send events with error handling
send_event() {
local endpoint="https://your.collection.domain/event"
local site_id="123456789"
local visitor_id="9e8d6d5f-143a-4a21-a7d5-7348b56e130d"
local payload='{
"events": [{
"name": "page.display",
"data": {
"page": "Homepage",
"page_chapter1": "Main"
}
}]
}'
# Send request with error handling
if response=$(curl -s -w "\n%{http_code}" \
-X POST \
-H "Content-Type: text/plain" \
-d "$payload" \
"${endpoint}?s=${site_id}&idclient=${visitor_id}"); then
http_code=$(echo "$response" | tail -n1)
response_body=$(echo "$response" | head -n -1)
if [ "$http_code" -eq 200 ]; then
echo "Events sent successfully"
else
echo "Error: HTTP $http_code - $response_body" >&2
exit 1
fi
else
echo "Error: Failed to send request" >&2
exit 1
fi
}
# Usage
send_event
```
```
--------------------------------
### Install piano_analytics plugin
Source: https://developers.piano.io/analytics/data-collection/sdks/flutter
Run this command in your Flutter project directory to install the piano_analytics package after adding it to pubspec.yaml.
```bash
flutter pub get
```
--------------------------------
### Buffer Start Event
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generates an event indicating the start of buffering, either at the launch of media or during playback. This can be a buffering or re-buffering event.
```APIDOC
## bufferStart
### Description
Generate an event of buffering at the launch of a media or during the playing. The `buffering.heartbeat` is sent before the `av.start` while the `rebuffering.heartbeat` is sent after an `av.start` is recorded on the `av_session_id`.
### Method Signature (JavaScript)
`bufferStart(cursorPosition[, callback, extraProps])`
### Parameters (JavaScript)
#### Path Parameters
- `cursorPosition` (number) - Required - Current cursor position (ms)
- `callback` (function) - Optional - Callback function to execute after hit sent
- `extraProps` (Object) - Optional - Custom properties
### Request Example (JavaScript)
```javascript
myMedia.bufferStart(
0,
function () {
console.log(
"Event av.buffer.start or av.rebuffer.start generated depending on the playback launch"
);
},
{ customProp: "customValue" }
);
```
### Method Signature (Android)
`bufferStart(cursorPosition, properties)`
### Parameters (Android)
#### Path Parameters
- `cursorPosition` (Int) - Required - Current cursor position (ms)
- `properties` vararg (Property) - Optional - Custom properties
### Request Example (Android)
```java
myMedia.bufferStart(
0,
Property(...),
Property(...)
)
```
### Method Signature (Java)
`func Media.bufferStart(cursorPosition, extraProps)`
### Parameters (Java)
#### Path Parameters
- `cursorPosition` (Int) - Required - Current cursor position (ms)
- `extraProps` (Map?) - Optional - Custom properties
### Request Example (Java)
```java
myMedia.bufferStart(
0,
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
### Method Signature (Swift)
`myMedia.bufferStart(cursorPosition: Int, extraProps: [String: Any]?)`
### Parameters (Swift)
#### Path Parameters
- `cursorPosition` (Int) - Required - Current cursor position (ms)
- `extraProps` ( [String: Any]? ) - Optional - Custom properties
### Request Example (Swift)
```swift
myMedia.bufferStart(
cursorPosition: 0,
extraProps: [
"av_content": "Content title",
...
]
)
```
```
--------------------------------
### Send a Single Event with Custom Protocol and Configuration
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/send-events-via-sdks
This advanced example demonstrates sending a single event with custom configurations and a custom protocol for pre-processing.
```swift
class PianoAnalyticsCustomProtocol: PianoAnalyticsWorkProtocol {
func onBeforeBuild(model: inout Model) -> Bool {
// add custom actions here
return true
}
func onBeforeSend(built: BuiltModel?, stored: [String: BuiltModel]?) -> Bool {
// add custom actions here
return true
}
}
pa.sendEvent(
Event("page.display", data: [
"page": "Page name",
"page_premium": false,
"page_authors": ["Clark Kent", "John Cena"]
]),
config: ConfigurationBuilder().withSite(123456789).build(),
p: PianoAnalyticsCustomProtocol()
)
```
--------------------------------
### Send Buffer Start Event in JavaScript
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generate a buffer start event in JavaScript. This event can be either 'av.buffer.start' or 'av.rebuffer.start' depending on context. Includes optional callback and custom properties.
```javascript
myMedia.bufferStart(
0,
function () {
console.log(
"Event av.buffer.start or av.rebuffer.start generated depending on the playback launch"
);
},
{ customProp: "customValue" }
);
```
--------------------------------
### Send Buffer Start Event in Apple (Swift)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generate a buffer start event in Apple platforms (Swift) using a dictionary for custom properties. This event can be either 'av.buffer.start' or 'av.rebuffer.start' depending on context.
```swift
myMedia.bufferStart(
cursorPosition: 0,
extraProps: [
"av_content": "Content title",
...
]
)
```
--------------------------------
### Example 1: Simple ascending sort
Source: https://developers.piano.io/analytics/data-api/parameters/sort-by
Sort results by device type in ascending order.
```APIDOC
### Example 1: Simple ascending sort
Sort results by device type in ascending order.
```json
{
"columns": ["device_type", "m_visits"],
"sort": ["device_type"]
}
```
```
--------------------------------
### Example 1: Absolute periods comparison
Source: https://developers.piano.io/analytics/data-api/parameters/period
This example demonstrates how to compare two distinct absolute date ranges using the 'period' parameter with 'p1' and 'p2' identifiers.
```APIDOC
## Example 1: Absolute periods comparison
Compare two specific date ranges.
```json
{
"period": {
"p1": [
{
"type": "D",
"start": "2019-10-20",
"end": "2019-10-24"
}
],
"p2": [
{
"type": "D",
"start": "2019-10-15",
"end": "2019-10-19"
}
]
}
}
```
```
--------------------------------
### Send Buffer Start Event in Android (Kotlin/Java) with HashMap
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generate a buffer start event in Android using a HashMap for custom properties. This event can be either 'av.buffer.start' or 'av.rebuffer.start' depending on context.
```java
myMedia.bufferStart(
0,
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
--------------------------------
### Simple property filter
Source: https://developers.piano.io/analytics/data-api/parameters/filter
Example demonstrating a simple filter for a specific property value.
```APIDOC
### Example 2: Simple property filter
Filter for desktop devices only.
```json
{
"filter": {
"property": {
"device_type": {
"$eq": "Desktop"
}
}
}
}
```
```
--------------------------------
### Compare Visits Across Multiple Periods
Source: https://developers.piano.io/analytics/data-api/parameters/properties-metrics
This example demonstrates how to compare a metric (m_visits) across different periods (p1 and p2) by prefixing the metric name with the period identifier.
```json
{
"columns": ["device_type", "p1.m_visits", "p2.m_visits"]
}
```
--------------------------------
### Example 2: Relative period with segment
Source: https://developers.piano.io/analytics/data-api/parameters/period
This example shows a monthly analysis using a relative period ('R') and an adaptive period ('AP') within a segment, illustrating dynamic date range calculations.
```APIDOC
## Example 2: Relative period with segment
Monthly analysis with adaptive segment period.
```json
{
"period": {
"p1": [
{
"type": "R",
"granularity": "M",
"startOffset": -1,
"endOffset": -1
}
]
},
"space": {
"s": [123456789]
},
"columns": ["visit_src", "m_visits"],
"segment": {
"section": {
"mode": "include",
"scope": "visitor_id",
"period": {
"p1": [
{
"type": "AP",
"granularity": "M",
"startOffset": -1,
"endOffset": -1
}
]
},
"content": {
"condition": {
"filter": {
"visit_geo_country": {
"$eq": "France"
}
}
}
}
}
}
}
```
```
--------------------------------
### Generate Playback Start Event in Android (Java)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Use this to generate the `av.start` event for Android. It accepts cursor position and optional custom properties using the `Property` class.
```java
myMedia.playbackStart(
0,
Property(...),
Property(...)
)
```
--------------------------------
### Generate Playback Start Event in Android (Kotlin)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Use this to generate the `av.start` event for Android with Kotlin. It accepts cursor position and custom properties as a `Map`.
```kotlin
myMedia.playbackStart(
0,
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
--------------------------------
### Instantiate Piano Analytics Tracker
Source: https://developers.piano.io/analytics/data-collection/sdks/android-java
Get an instance of the PianoAnalytics tracker by passing the application context. This should be done before using the SDK's functionalities.
```java
PianoAnalytics pa = PianoAnalytics.getInstance(getApplicationContext());
```
--------------------------------
### Make Authenticated API Request in Ruby
Source: https://developers.piano.io/analytics/data-api/getting-started/authentication
This Ruby example shows how to set the 'x-api-key' header and send a POST request with a JSON body to the API.
```ruby
request["x-api-key"] = 'YOURAPIKEY'
request.body = "{
\"columns\": [
\"visit_device_type\",
\"m_visits\",
\"m_users\"
],
\"sort\": [
\"-m_visits\"
],
\"space\": {
\"s\": [
429023
]
},
\"period\": {
\"p1\": [
{
\"type\": \"D\",
\"start\": \"2019-10-24\",
\"end\": \"2019-10-24\"
}
]
},
\"max-results\": 50,
\"page-num\": 1
}"
response = http.request(request)
puts response.read_body
```
--------------------------------
### Send Events - Android (Java)
Source: https://developers.piano.io/analytics/event-composer?name=cart.update&props=%5B%5B%22cart_id%22%2C%22LAPW221C%22%2Ctrue%5D%2C%5B%22cart_currency%22%2C%22EUR%22%5D%2C%5B%22cart_turnovertaxincluded%22%2C%221399.9%22%5D%2C%5B%22cart_turnovertaxfree%22%2C%221120.9%22%5D%2C%5B%22cart_quantity%22%2C%221%22%5D%2C%5B%22cart_nbdistinctproduct%22%2C%221%22%5D%5D
This example demonstrates sending events with properties on Android using the Java SDK. Initialize the PianoAnalytics SDK before use.
```java
PianoAnalytics.getInstance().sendEvents(
Event.Builder("")
.properties(
)
.build()
)
```
--------------------------------
### Basic Configuration Methods
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript
Use `setConfiguration` for individual settings or `setConfigurations` for bulk updates. These methods configure essential parameters like site ID and collection domain.
```javascript
pa.setConfiguration("site", 123456789); // your site id
pa.setConfiguration("collectDomain", "https://.pa-cd.com"); // your collection domain
// or bulk configuration (recommended)
pa.setConfigurations({
site: 123456789,
collectDomain: "https://.pa-cd.com",
});
```
--------------------------------
### Send cart.creation event in Apple (Swift)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/sales-insights
Example of sending a cart creation event using the Apple SDK in Swift. Properties are defined using a dictionary, and `cart_id` is mandatory.
```swift
await _pianoAnalytics.sendEvents(events: [
Event(name: "cart.creation", properties: [
Property.string(name: "cart_id", value: "LAPW221C"), // mandatory
Property.string(name: "cart_currency", value: "EUR"),
Property.int(name: "cart_turnovertaxincluded", value: 1399.9),
Property.int(name: "cart_turnovertaxfree", value: 1120.9),
Property.int(name: "cart_quantity", value: 1),
Property.int(name: "cart_nbdistinctproduct", value: 1),
])
]);
```
--------------------------------
### Configure Gradle for Settings Repositories
Source: https://developers.piano.io/analytics/data-collection/sdks/android-java
If you encounter the 'Build was configured to prefer settings repositories over project repositories' error after manual installation, add this line to your project-level settings.gradle file.
```gradle
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
```
--------------------------------
### Generate Playback Start Event in Apple (Swift)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Use this to generate the `av.start` event for Apple platforms with Swift. It accepts cursor position and custom properties as an optional `[String: Any]` dictionary.
```swift
myMedia.playbackStart(
cursorPosition: 0,
extraProps: [
"av_content": "Content title",
...
]
)
```
--------------------------------
### Get Privacy Mode in Swift
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/privacy
Use `pa.privacyGetMode()` with a completion handler to asynchronously get the current privacy mode.
```swift
pa.privacyGetMode(privacyMode -> {
// do something with user
});
```
--------------------------------
### Valid Date Property Format Example
Source: https://developers.piano.io/analytics/data-collection/import/catalogs
When importing date-related properties, use the UTC ISO 8601 format as shown in this example.
```text
2025-11-16T04:25:03.000Z
```
--------------------------------
### Initializing Media Helper (Android)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Initializes the media helper with content ID and a custom session ID.
```APIDOC
## Initialize Media Helper (Android)
### Description
Initializes the media helper with a content ID and an optional custom session ID.
### Method
`PianoAnalytics.getInstance().mediaHelper(contentId, customSessionId)`
### Parameters
* `contentId` (string) - The ID of the content.
* `customSessionId` (string) - Optional. A custom session ID to override the default `av_session_id`.
### Request Example
```kotlin
val myMedia = PianoAnalytics.getInstance().mediaHelper("contentId", "custom-session-id")
```
```
--------------------------------
### PianoAnalytics Initialization
Source: https://developers.piano.io/analytics/data-collection/sdks/flutter
Initialize the PianoAnalytics SDK with your site ID, collection domain, and other configuration options.
```APIDOC
## PianoAnalytics Initialization
### Description
Initialize `PianoAnalytics` with your site and collect domain in your application initialization.
### Method Signature
```dart
PianoAnalytics({
required int site,
required String collectDomain,
VisitorIDType? visitorIDType,
int? storageLifetimeVisitor,
VisitorStorageMode? visitorStorageMode,
bool? ignoreLimitedAdvertisingTracking,
String? visitorId
});
```
### Initialization Example
```dart
import 'package:piano_analytics/piano_analytics.dart';
...
final _pianoAnalytics = PianoAnalytics(
site: 123456789,
collectDomain: "xxxxxxx.pa-cd.com",
visitorIDType: VisitorIDType.uuid,
storageLifetimeVisitor: 395,
visitorStorageMode: VisitorStorageMode.fixed,
ignoreLimitedAdvertisingTracking: true,
visitorId: "97c7db4e-4514-4b8e-b693-bd6b57043cc1"
);
await _pianoAnalytics.init();
```
```
--------------------------------
### Initialize Piano Analytics Tracker
Source: https://developers.piano.io/analytics/data-collection/sdks/android-kotlin
Configure and initialize the tracker with your site ID and collection domain. Pass the application context during initialization.
```kotlin
val configuration = Configuration.Builder(
collectDomain = ".pa-cd.com",
site = 123456789,
// you can set other configurations here
).defaultPrivacyMode(...)
// or set configurations via builder methods
.build()
PianoAnalytics.init(applicationContext, configuration)
```
--------------------------------
### Track Audio/Video Buffer Events
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Track buffer start and rebuffer start events for audio and video content. Provide the current playback position and content details as properties.
```java
// Buffer tagging
myMedia.track(
"av.buffer.start",
new HashMap() {{
put("av_position", 0);
}},
new HashMap() {{
put("av_content", "Content title");
...
}}
);
// Re-buffer tagging
myMedia.track(
"av.rebuffer.start",
new HashMap() {{
put("av_position", 10);
}},
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
--------------------------------
### playbackStart
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generates a playback start event (`av.start`). This event is crucial for initiating automatic `av.heartbeat` events, which accurately track playback duration. The `av.heartbeat` events are configured according to the media instance settings.
```APIDOC
## playbackStart(cursorPosition[, callback, extraProps])
### Description
Generates a playback start event (`av.start`). This allows automatic `av.heartbeat` events to be sent, accurately tracking playback time.
### Parameters
#### Path Parameters
* `cursorPosition` (number) - Required - Current cursor position in milliseconds.
* `callback` (function) - Optional - Callback function to execute after the event is sent.
* `extraProps` (Object) - Optional - Custom properties to include with the event.
### Request Example
```javascript
myMedia.playbackStart(
0,
function () {
console.log("Event av.start generated");
},
{ customProp: "customValue" }
);
```
## playbackStart(cursorPosition, properties...)
### Description
Generates a playback start event (`av.start`) using varargs for properties.
### Parameters
#### Path Parameters
* `cursorPosition` (Int) - Required - Current cursor position in milliseconds.
* `properties` (Property) - Optional - Custom properties.
### Request Example
```java
myMedia.playbackStart(
0,
Property(...),
Property(...)
)
```
## func Media.playbackStart(cursorPosition, extraProps)
### Description
Generates a playback start event (`av.start`) for Android.
### Parameters
#### Path Parameters
* `cursorPosition` (Int) - Required - Current cursor position in milliseconds.
* `extraProps` (Map?) - Optional - Custom properties.
### Request Example
```java
myMedia.playbackStart(
0,
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
## myMedia.playbackStart(cursorPosition: Int, extraProps: [String: Any]?)
### Description
Generates a playback start event (`av.start`) for Swift/Objective-C.
### Parameters
#### Path Parameters
* `cursorPosition` (Int) - Required - Current cursor position in milliseconds.
* `extraProps` ([String: Any]?) - Optional - Custom properties.
### Request Example
```swift
myMedia.playbackStart(
cursorPosition: 0,
extraProps: [
"av_content": "Content title",
...
]
)
```
```
--------------------------------
### Initialize Media with Custom Session ID (Java)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Create a new Media instance with a custom session ID. This is an alternative to the SDK's default session management.
```java
Media myMedia = new Media(pa, "custom-session-id");
```
--------------------------------
### Initializing Media (Java)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Initializes a media object with a custom session ID.
```APIDOC
## Initialize Media (Java)
### Description
Initializes a media object with an optional custom session ID.
### Method
`new Media(pa, sessionId)`
### Parameters
* `pa` (PianoAnalytics) - The PianoAnalytics instance.
* `sessionId` (string) - Optional. A custom session ID to override the default `av_session_id`.
### Request Example
```java
Media myMedia = new Media(pa, "custom-session-id");
```
```
--------------------------------
### Send Buffer Start Event in Android (Kotlin/Java)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generate a buffer start event in Android using the Property vararg for custom properties. This event can be either 'av.buffer.start' or 'av.rebuffer.start' depending on context.
```java
myMedia.bufferStart(
0,
Property(...),
Property(...)
)
```
--------------------------------
### Apple Media Instantiation (Swift)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Instantiate the Media object in Swift for Apple platforms, including options for heartbeat durations and session ID.
```APIDOC
## Apple Media Instantiation
### Description
Import `io.piano.analytics.avinsights.Media` and instantiate the `Media` object in Swift to track media events. You can initialize it with a `PianoAnalytics` instance and an optional session ID. Heartbeat management is configured using dedicated methods.
### Method
`Media(pa: PianoAnalytics, sessionId: String?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Description | Example |
|---|---|---|---|
| `pa` | `PianoAnalytics` | Tracker instance. | `pa` |
| `sessionId` (optional) | `String` | Session ID of the playback. Automatically managed by the SDK, but can be overridden. | - |
### Request Example
```swift
import io.piano.analytics.avinsights.Media;
// Initialize with PianoAnalytics instance
Media myMedia = new Media(pa);
// Initialize with PianoAnalytics instance and sessionId
Media myMedia = new Media(pa, sessionId);
```
### Response
N/A (This is a constructor)
## Setting Heartbeat Durations (Apple)
### Description
Configure automatic heartbeat management for playback and buffering using `setHeartbeat` and `setBufferHeartbeat` methods on the `Media` object.
### Method
`myMedia.setHeartbeat(heartbeat)`
`myMedia.setBufferHeartbeat(bufferHeartbeat)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Description | Example |
|---|---|---|---|
| `heartbeat` | `[Int: Int]?` | Delay between two heartbeats during playback (minimum delay is 5sec). A map can specify different delays for different playback times. | `[0:5, 1:10, 5:60]` |
| `bufferHeartbeat` | `[Int: Int]?` | Delay between two heartbeats during buffering (minimum delay is 1sec). A map can specify different delays for different buffering times. | `[0:5, 1:10, 5:60]` |
### Request Example
```swift
myMedia.setHeartbeat(heartbeat: [
0: 5,
1: 10,
5: 60
])
myMedia.setBufferHeartbeat(bufferHeartbeat: [
0: 5,
1: 10,
5: 60
])
```
### Response
N/A
```
--------------------------------
### Android Media Instantiation (Java/Kotlin)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Instantiate the Media object in Android using Java or Kotlin, with options for heartbeat durations and session ID.
```APIDOC
## Android Media Instantiation
### Description
Instantiate the `AVMedia` object in Android to manage media events. You can provide a `PianoAnalytics` instance and an optional session ID. Heartbeat management is handled via dedicated methods.
### Method
`AVMedia(pa: PianoAnalytics, sessionId: String?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Description | Example |
|---|---|---|---|
| `pa` | `PianoAnalytics` | Tracker instance. | `pa` |
| `sessionId` (optional) | `String?` | Session ID of the playback. Automatically managed by the SDK, but can be overridden. | - |
### Request Example
```kotlin
var myMedia = AVMedia(pa: PianoAnalytics, sessionId: String? = null)
// Example with only PianoAnalytics instance
var myMedia = AVMedia(pa: pa)
```
### Response
N/A (This is a constructor)
## Setting Heartbeat Durations (Android)
### Description
Configure automatic heartbeat management for playback and buffering using `setHeartbeat` and `setBufferHeartbeat` methods on the `AVMedia` object.
### Method
`myMedia.setHeartbeat(heartbeat: [Int: Int]?)`
`myMedia.setBufferHeartbeat(bufferHeartbeat: [Int: Int]?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Parameter | Type | Description | Example |
|---|---|---|---|
| `heartbeat` | `[Int: Int]?` | Delay between two heartbeats during playback (minimum delay is 5sec). A map can specify different delays for different playback times. | `[0:5, 1:10, 5:60]` |
| `bufferHeartbeat` | `[Int: Int]?` | Delay between two heartbeats during buffering (minimum delay is 1sec). A map can specify different delays for different buffering times. | `[0:5, 1:10, 5:60]` |
### Request Example
```kotlin
myMedia.setHeartbeat(heartbeat: [
0: 5,
1: 10,
5: 60
])
myMedia.setBufferHeartbeat(bufferHeartbeat: [
0: 5,
1: 10,
5: 60
])
```
### Response
N/A
```
--------------------------------
### Shell (curl) API Call Example
Source: https://developers.piano.io/analytics/data-api/getting-started/first-call
This example demonstrates how to make a POST request using curl in a shell environment. Remember to replace 'YOURAPIKEY' with your valid API key. The Content-Type header is set to application/json.
```shell
curl -X POST \
https://api.atinternet.io/v3/data/getData \
-H 'x-api-key: YOURAPIKEY' \
-H 'Content-Type: application/json' \
-d '{ \
"columns": [ \
"device_type", \
"m_visits", \
"m_users" \
],
"sort": [ \
"-m_visits" \
],
"space": {
"s": [429023] \
},
"period": {
"p1": [ \
{
"type": "D",
"start": "2019-10-24",
"end": "2019-10-24"
}
]
},
"max-results": 50,
"page-num": 1
}'
```
--------------------------------
### Get Sites of a Team API Endpoint
Source: https://developers.piano.io/analytics/configuration/routes/get-sites-of-a-team
Use this GET request to retrieve sites belonging to a specific team. The `teamId` is mandatory, while `page` is also required for pagination. `size` is optional for specifying the number of results per page.
```HTTP
GET v2/teams/{teamId}/sites?page=2&size=10
```
--------------------------------
### Import Media Class in Java
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Import the Media class from the io.piano.analytics.avinsights package in Java.
```java
import io.piano.analytics.avinsights.Media;
```
--------------------------------
### Get Teams
Source: https://developers.piano.io/analytics/configuration/routes/get-teams
Retrieves a list of teams. Supports pagination and sorting.
```APIDOC
## GET v2/teams
### Description
Retrieves a list of teams, sorted alphabetically by name. Supports pagination to manage the number of results returned.
### Method
GET
### Endpoint
`v2/teams`
### Parameters
#### Query Parameters
- **page** (Number) - Required - The results page number to retrieve.
- **size** (Number) - Optional - The number of elements to return per page. Defaults to 50, with a maximum of 100.
### Response
#### Success Response (200 OK)
Returns a JSON object containing metadata about the request and a list of teams.
- **metadata** (Object) - Contains request metadata including requestId, count, page, and size.
- **requestId** (String) - The unique identifier for the request.
- **count** (Number) - The total number of teams available.
- **page** (Number) - The current page number.
- **size** (Number) - The number of teams returned per page.
- **data** (Object) - Contains the list of teams.
- **teams** (Array) - A list of team objects.
- **id** (String) - The unique identifier for the team.
- **name** (String) - The name of the team.
- **availableForSharing** (Boolean) - Indicates if the team is available for sharing.
- **allUsers** (Boolean) - Indicates if the team includes all users.
- **allSites** (Boolean) - Indicates if the team includes all sites.
### Response Example
```json
{
"metadata": {
"requestId" :"",
"count": 0,
"page": 0,
"size": 0
},
"data": {
"teams": [
{
"id": "",
"name": "",
"availableForSharing": true,
"allUsers": true,
"allSites": true
}
]
}
}
```
```
--------------------------------
### Generate Playback Start Event in JavaScript
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Use this to generate the `av.start` event, which is the first media frame. This enables automatic `av.heartbeat` events. It accepts cursor position, an optional callback, and custom properties.
```javascript
myMedia.playbackStart(
0,
function () {
console.log("Event av.start generated");
},
{ customProp: "customValue" }
);
```
--------------------------------
### Initialize Piano Consents
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/consent
Add initialization for consents using `PianoConsents.init`. You can specify `requireConsent` and `defaultPurposes`.
```kotlin
val pianoConsents = PianoConsents.init(
applicationContext,
ConsentConfiguration(
requireConsent = true,
defaultPurposes = mapOf(...) // if needed
)
)
```
--------------------------------
### Rebuffer Heartbeat Event
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Generate a buffering heartbeat event after the playback starts.
```APIDOC
## rebufferHeartbeat
### Description
Generate a buffering heartbeat after the playback starts event.
### Method Signature
`rebufferHeartbeat([callback, extraProps])`
### Parameters
#### Path Parameters
- `callback` (function) - Optional - Callback function to execute after hit sent
- `extraProps` (Object) - Optional - Custom properties
### Request Example
```javascript
myMedia.rebufferHeartbeat(
function () {
console.log("Event av.rebuffer.heartbeat generated");
},
{ customProp: "customValue" }
);
```
### Method Signature
`rebufferHeartbeat(properties)`
### Parameters
#### Path Parameters
- `properties` (Property) - Optional - Custom properties (vararg)
### Request Example
```javascript
myMedia.rebufferHeartbeat(
Property(...),
Property(...)
)
```
### Method Signature
`rebufferHeartbeat(extraProps)`
### Parameters
#### Path Parameters
- `extraProps` (Map) - Optional - Custom properties
### Request Example
```java
myMedia.rebufferHeartbeat(
new HashMap() {{
put("av_content", "Content title");
...
}}
);
```
### Method Signature
`rebufferHeartbeat(extraProps)`
### Parameters
#### Path Parameters
- `extraProps` ([String: Any]) - Optional - Custom properties
### Request Example
```swift
myMedia.rebufferHeartbeat(
extraProps: [
"av_content": "Content title",
...
]
)
```
```
--------------------------------
### Initialize Tracker and Send Event
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript-browserless
Initialize a tracker instance with site ID and collection domain, then send a page display event. For CommonJS environments, use require.
```javascript
import { pianoAnalytics } from "piano-analytics-js";
// for commonJS environment you can do the following
// const pianoAnalytics = require('piano-analytics-js').pianoAnalytics;
pianoAnalytics.setConfigurations({"
site: 123456789,
collectDomain: "https://my.collect.domain",
});
pianoAnalytics.sendEvent("page.display", {"
page: "Page label",
});
```
--------------------------------
### Get Privacy Mode in Android (Kotlin)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/privacy
Retrieve the current privacy mode from `privacyModesStorage`.
```kotlin
val privacyModesStorage = PianoAnalytics.getInstance().privacyModesStorage
val currentPrivacyMode = privacyModesStorage.currentMode
```
--------------------------------
### Instantiate Media Object in Java
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Declare a Media object in Java, providing the tracker instance and an optional session ID.
```java
Media myMedia = new Media(pa);
// or
Media myMedia = new Media(pa, sessionId);
```
--------------------------------
### Enable All Instant Tracking Features
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/instant-tracking
Load the Piano Analytics SDK and enable all instant tracking features by setting `instantTracking: true`. Ensure `site` and `collectDomain` match your organization's settings.
```javascript
(function (_config) {
var script = document.createElement("script");
script.src = "https://tag.aticdn.net/piano-analytics.js";
script.async = true;
script.dataset.config = JSON.stringify(_config);
document.head.appendChild(script);
})({
site: 123456789,
collectDomain: "https://xxxxxxx.pa-cd.com",
instantTracking: true,
consentDefaultMode: "opt-in",
});
```
--------------------------------
### Get Privacy Mode in JavaScript
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/privacy
Call `pa.privacy.getMode()` to retrieve the current privacy mode as a string.
```javascript
pa.privacy.getMode(); // Return a string with the Privacy Mode value
```
--------------------------------
### Complex filter with logical operations
Source: https://developers.piano.io/analytics/data-api/parameters/filter
Example demonstrating a complex filter with logical operations for metrics and properties.
```APIDOC
### Example 1: Complex filter with logical operations
Filter for visits equal to 19 AND device type is Tablet or Desktop AND source starts with "Referrer".
```json
{
"filter": {
"metric": {
"m_visits": {
"$eq": 19
}
},
"property": {
"$AND": [
{
"$OR": [{
"device_type": {
"$in": ["Tablet", "Desktop"]
}
}]
},
{
"visit_src": {
"$start": "Referrer"
}
}
]
}
}
}
```
```
--------------------------------
### Configure Piano Analytics SDK Loading
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/consent
The configuration of the Consents feature uses the global object `window.pdl`, which must be defined and populated before loading the SDK. Ensure `window.pdl` is initialized.
```html
...
```
--------------------------------
### Example 2: Descending sort by metric
Source: https://developers.piano.io/analytics/data-api/parameters/sort-by
Sort results by visits in descending order (highest first).
```APIDOC
### Example 2: Descending sort by metric
Sort results by visits in descending order (highest first).
```json
{
"columns": ["device_type", "m_visits"],
"sort": ["-m_visits"]
}
```
```
--------------------------------
### Initializing Media with Custom Session ID (JavaScript)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Demonstrates how to create a new media object with a custom session ID, overriding the default `av_session_id`.
```APIDOC
## Initialize Media with Custom Session ID
### Description
Creates a new media object with an optional custom session ID.
### Method
`new pa.avInsights.Media(mediaDuration, mediaPlayedDuration, sessionId)`
### Parameters
* `mediaDuration` (number) - The total duration of the media.
* `mediaPlayedDuration` (number) - The duration of the media played so far.
* `sessionId` (string) - Optional. A custom session ID to override the default `av_session_id`.
### Request Example
```javascript
var myMedia = new pa.avInsights.Media(5, 5, "custom_session_id");
```
```
--------------------------------
### Get Privacy Mode in Objective-C
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/privacy
Use `pa.privacyGetMode(completionHandler:)` to asynchronously retrieve the current privacy mode.
```objectivec
pa.privacyGetMode { privacyMode in
print(privacyMode)
}
```
--------------------------------
### Send Event - Flutter
Source: https://developers.piano.io/analytics/event-composer?name=cart.creation&props=%5B%5B%22cart_id%22%2C%22LAPW221C%22%2Ctrue%5D%2C%5B%22cart_currency%22%2C%22EUR%22%5D%2C%5B%22cart_turnovertaxincluded%22%2C%221399.9%22%5D%2C%5B%22cart_turnovertaxfree%22%2C%221120.9%22%5D%2C%5B%22cart_quantity%22%2C%221%22%5D%2C%5B%22cart_nbdistinctproduct%22%2C%221%22%5D%5D
This example shows how to send events using the Flutter SDK. Events are sent as a list.
```dart
await _pianoAnalytics.sendEvents(events: [
Event(name: "", properties: [
])
]);
```
--------------------------------
### Add Piano Analytics SDK via Carthage
Source: https://developers.piano.io/analytics/data-collection/sdks/ios-swift
Integrate the SDK by adding its GitHub repository to your Cartfile. Ensure you specify a compatible version.
```bash
github "at-internet/piano-analytics-apple" ~> 3.0
```
--------------------------------
### SDK Configuration Before Loading
Source: https://developers.piano.io/analytics/data-collection/sdks/javascript
Define global configurations on the `window._pac` object before the SDK script is loaded. This allows for customization of cookie domains, paths, and other SDK behaviors.
```javascript
window._pac = window._pac || {};
;
```
--------------------------------
### Authenticate API Request with cURL
Source: https://developers.piano.io/analytics/data-api/getting-started/authentication
Example of how to authenticate a cURL request by including the API Key in the 'x-api-key' header.
```shell
curl "https://api.atinternet.io/v3/data/getData" \
-H "x-api-key: YOURAPIKEY" \
```
--------------------------------
### Set SDK Configuration
Source: https://developers.piano.io/analytics/data-collection/sdks/android-java
Use this method to set the SDK's configuration. Ensure you have the correct collection domain and site ID.
```java
pa.setConfiguration(new Configuration.Builder()
.withCollectDomain(".pa-cd.com")
.withSite(123456789)
.build()
);
```
--------------------------------
### Send cart.update Event in Apple
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/sales-insights
Example of sending the cart.update event using the Apple SDK. The cart_id must be provided.
```swift
await _pianoAnalytics.sendEvents(events: [
Event(name: "cart.update", properties: [
Property.string(name: "cart_id", value: "LAPW221C"), // mandatory
Property.string(name: "cart_currency", value: "EUR"),
Property.int(name: "cart_turnovertaxincluded", value: 1399.9),
Property.int(name: "cart_turnovertaxfree", value: 1120.9),
Property.int(name: "cart_quantity", value: 1),
Property.int(name: "cart_nbdistinctproduct", value: 1),
])
]);
```
--------------------------------
### Send internal_search_result.click Event (Android)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/standard-events
This example shows how to send the 'internal_search_result.click' event with standard properties using the Android SDK.
```java
PianoAnalytics.getInstance().sendEvents(
Event.Builder("internal_search_result.click")
.properties(
Property(PropertyName("ise_keyword"), "daft"),
Property(PropertyName("ise_click_rank"), 2),
Property(PropertyName("ise_page"), 1),
)
.build()
)
```
```java
pa.sendEvent(new Event("internal_search_result.click", new HashMap() {{
put("ise_keyword", "daft");
put("ise_click_rank", 2);
put("ise_page", 1);
}}));
```
--------------------------------
### Send internal_search_result.display Event (Android)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/standard-events
This example shows how to send the 'internal_search_result.display' event with standard properties using the Android SDK.
```java
PianoAnalytics.getInstance().sendEvents(
Event.Builder("internal_search_result.display")
.properties(
Property(PropertyName("ise_keyword"), "daft"),
Property(PropertyName("ise_page"), 2),
)
.build()
)
```
```java
pa.sendEvent(new Event("internal_search_result.display", new HashMap() {{
put("ise_keyword", "daft");
put("ise_page", 2);
}}));
```
--------------------------------
### Initializing Media (Swift)
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/av-insights
Initializes an AVMedia object with a custom session ID.
```APIDOC
## Initialize Media (Swift)
### Description
Initializes an AVMedia object with an optional custom session ID.
### Method
`AVMedia(pa: PianoAnalytics, sessionId: String)`
### Parameters
* `pa` (PianoAnalytics) - The PianoAnalytics instance.
* `sessionId` (String) - Optional. A custom session ID to override the default `av_session_id`.
### Request Example
```swift
var myMedia = AVMedia(pa: pa, sessionId: "custom-session-id")
```
```
--------------------------------
### Get a Privacy Mode
Source: https://developers.piano.io/analytics/data-collection/how-to-send-events/privacy
Retrieve the current privacy mode being used by the SDK. This allows you to check the active privacy settings.
```APIDOC
## Get a Privacy Mode
### JavaScript
Method:
`pa.privacy.getMode()`
```javascript
pa.privacy.getMode(); // Return a string with the Privacy Mode value
```
### Android
Method:
`PianoAnalytics.getInstance().privacyModesStorage.currentMode`
```kotlin
val privacyModesStorage = PianoAnalytics.getInstance().privacyModesStorage
val currentPrivacyMode = privacyModesStorage.currentMode
```
### iOS
Method:
`func PianoAnalytics.privacyGetMode(completionHandler: ((_ privacyMode: String) -> Void)?)`
```swift
pa.privacyGetMode { privacyMode in
print(privacyMode)
}
```
```
--------------------------------
### Get Users
Source: https://developers.piano.io/analytics/configuration/routes/get-users
Retrieves a list of the organization's active and suspended users. Supports pagination via query parameters.
```APIDOC
## GET v2/users
### Description
Retrieves a list of the organization's active and suspended users. Results are sorted alphabetically by email address.
### Method
GET
### Endpoint
`/v2/users`
### Parameters
#### Query Parameters
- **page** (Number) - Required - The results page number.
- **size** (Number) - Optional - The number of elements per page. Defaults to 50, with a maximum of 100.
### Response
#### Success Response (200 OK)
- **metadata** (Object) - Contains pagination information and total count.
- **requestId** (string)
- **count** (Number) - The total number of elements.
- **page** (Number) - The current page number.
- **size** (Number) - The number of elements per page.
- **data** (Object)
- **users** (Array) - A list of user objects.
- **id** (string)
- **lastName** (string)
- **firstName** (string)
- **email** (string)
- **suspensionStartDate** (ISO string) - The date the user was suspended, if applicable.
#### Response Example
```json
{
"metadata": {
"requestId": "",
"count": 10,
"page": 1,
"size": 10
},
"data": {
"users": [
{
"id": "user-123",
"lastName": "Doe",
"firstName": "John",
"email": "john.doe@example.com",
"suspensionStartDate": null
},
{
"id": "user-456",
"lastName": "Smith",
"firstName": "Jane",
"email": "jane.smith@example.com",
"suspensionStartDate": "2023-10-27T10:00:00Z"
}
]
}
}
```
```