Code Sample: Video Analytics Report by Country and Day

Product(s)
Video Cloud
Role(s)
API Developer
Topic(s)
Analytics
API(s)
Analytics API

In this sample, you will learn how to create a report showing the total video views by country for each day over a selected period. You can also filter the returned data by date and/or country.

Dependencies

3rd party libraries used in this sample:

Pikaday

Inputs

Basic Information

By default, you will get results from the Brightcove Training Videos account.

Date Range for Report

Note: the date range must be set before you fetch the data. If you wish to set a new date range, you will need to refresh the page.

Start:

End:

Get Country Data

 

Results

Date: Country:

Country Video Views

Code for the sample

The JavaScript code for this sample is shown below — view source to see the full page code.

 


    var BCLS = (function (window, document, Pikaday) {
    'use strict';
    var proxyURL = 'https://solutions.brightcove.com/bcls/bcls-proxy/analyitcs-by-player-day-proxy.php',
        callNumber = 0,
        callType = '',
        // call limit will be reset once we know how many countries have data for the period
        callLimit = 200,
        useMyAccount = document.getElementById('useMyAccount'),
        basicInfo = document.getElementById('basicInfo'),
        accountID = document.getElementById('accountID'),
        client_id = document.getElementById('client_id'),
        client_secret = document.getElementById('client_secret'),
        dateSelector = document.getElementById('dateSelector'),
        reportTableBody = document.getElementById('reportTableBody'),
        account_id = '1752604059001',
        currentDayIndex = 0,
        currentDay,
        dayMax,
        daysObj = {},
        daysArray = [],
        dateToMS,
        dateFromMS,
        fromPicker,
        toPicker,
        analyticsData = {},
        dayMS,
        fromDate = document.getElementById('fromDatePicker'),
        toDate = document.getElementById('toDatePicker'),
        countrySelector = document.getElementById('countrySelector'),
        getData = document.getElementById('getData'),
        gettingDataDisplay = document.getElementById('gettingDataDisplay'),
        today = new Date(),
        weekAgo = new Date(today.valueOf() - 604800000);
        /**
         * Logging function - safe for IE
         * @param  {string} context description of the data
         * @param  {*} message the data to be logged by the console
         * @return {}
         */
        function bclslog(context, message) {
            if (window['console'] && console['log']) {
              console.log(context, message);
            }
            return;
        }
        // more robust test for strings 'not defined'
        function isDefined (v) {
            if (v === '' || v === null || v === undefined || v === NaN) {
              return false;
            }
            return true;
        }
        /**
         * function that returns iso date for JS date object
         * @param {date} date the date object
         * @return {string} iso date string
         */
        function dateToISO(date) {
            var y = date.getFullYear(),
                m = date.getMonth(),
                d = date.getDate(),
                isoDate;
            y = y.toString();
            m = m + 1;
            if (m ' + analyticsData[day].date + '';
                        iMax = analyticsData[day].items.length;
                        for (i = 0; i ' + item.country_name + '
' + item.video_view + '';
                        }
                    }
                    reportTableBody.innerHTML = displayStr;
                } else {
                    // we have a selected country - display values for all dates
                    selectedCountry = getSelectValue(countrySelector);
                    displayStr = '';
                    for (day in analyticsData) {
                        displayStr += '' + analyticsData[day].date + '';
                        iMax = analyticsData[day].items.length;
                        for (i = 0; i ' + item.country_name + '
' + item.video_view + '';
                            }
                        }
                    }
                    reportTableBody.innerHTML = displayStr;
                }
            } else if (getSelectValue(countrySelector) === 'all') {
                // a specific data is selected - display all countries for that data
                displayStr = '';
                selectedDate = getSelectValue(dateSelector);
                day = analyticsData[selectedDate];
                displayStr += '' + day.date + '';
                iMax = day.items.length;
                for (i = 0; i ' + item.country_name + '
' + item.video_view + '';
                }
                reportTableBody.innerHTML += displayStr;
            } else {
                // a specific date and country are selected - display country views for that date
                displayStr = '';
                selectedDate = getSelectValue(dateSelector);
                selectedCountry = getSelectValue(countrySelector);
                day = analyticsData[selectedDate];
                displayStr += '' + day.date + '';
                iMax = day.items.length;
                for (i = 0; i ' + item.country_name + '
' + item.video_view + '';
                    }
                }
                reportTableBody.innerHTML += displayStr;
            }
        }
        /**
         * make API calls
         * @param {String} callURL the full URL for the API request
         */
        function makeAnalyticsCall(callURL) {
            var httpRequest = new XMLHttpRequest(),
                options = {},
                newItem = {},
                data,
                requestParams,
                newEl,
                txt,
                // response handler
                getResponse = function () {
                    var i,
                        j,
                        k,
                        player,
                        video,
                        itemsMax,
                        str,
                        analytics,
                        item,
                        newItem = {},
                        thisVideo;
                    try {
                        if (httpRequest.readyState === 4) {
                              if (httpRequest.status >= 200 && httpRequest.status ' + item.country_name + '';
                                }
                                countrySelector.innerHTML = '

' + str; gettingDataDisplay.innerHTML = 'Country data retrieved!'; getData.innerHTML = 'Get Analytics Data'; // now get the analytics data getAnalyticsData(); callLimit = itemsMax; break; case 'analytics': // add the data values to the value object analyticsData[currentDay] = {}; analyticsData[currentDay].date = currentDay; analyticsData[currentDay].items = []; itemsMax = data.items.length; for (i = 0; i ' + item + ''; } dateSelector.innerHTML = '

' + str; currentDayIndex = 0; currentDay = daysArray[0]; getCountryData(); } // add date pickers to the date input fields fromPicker = new Pikaday({ field: fromDate, format: 'YYYY-MM-DD' }); toPicker = new Pikaday({ field: toDate, format: 'YYYY-MM-DD' }); // default date range values toDate.value = dateToISO(today); fromDate.value = dateToISO(weekAgo); getData.addEventListener('click', initializeData); countrySelector.addEventListener('change', displayData); dateSelector.addEventListener('change', displayData); useMyAccount.addEventListener('click', function () { if (basicInfo.getAttribute('style') === 'display:none;') { basicInfo.setAttribute('style', 'display:block;'); useMyAccount.innerHTML = 'Use Sample Account'; } else { basicInfo.setAttribute('style', 'display:none;'); useMyAccount.innerHTML = 'Use My Account Instead'; } }); })(window, document, Pikaday);