css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <section class="bcls-section" id="workingSample">
  <h2>Daily Unique Users Report</h2>

  <fieldset class="bcls-fieldset">
    <legend>Input</legend>

    <p>If you do not enter account information, a Brightcove sample account will be used.</p>

    <p>Account id: <input id="account_id" type="text" value="" placeholder="1752604059001" /></p>

    <p>Client id: <input id="client_id" type="text" size="60" value="" placeholder="c5d0a622-5479-46d8-8d8a-5f034b943fab" /></p>

    <p>Client secret: <input id="client_secret" type="text" size="60" value="" placeholder="w7NQYu0vUloM4GYYy2SXAxrvyFpt8fwI35qAFZcS13" /></p>

    <p><strong>Date Range:</strong></p>

    <table class="bcls-table">
      <tbody class="bcls-table__body">
        <tr>
          <td>
            From date<br>
            (default: 30 days ago)
          </td>
          <td>
            To date<br>
            (default: today)
          </td>
        </tr>
        <tr>
          <td><input id="fromDate" class="date-field" style="width:200px;font-size:1.3rem;" /></td>
          <td><input id="toDate" class="date-field" style="width:200px;font-size:1.3rem;" /></td>
        </tr>
      </tbody>
    </table>

    <p><button class="bcls-button" id="makeReport">Generate the Report</button></p>

    <p>Current API request</p>

    <textarea id="apiRequest" class="bcls-request">API requests will appear here...</textarea>

    <p>Current API response</p>

    <textarea id="apiResponse" class="bcls-code">API resonses will appear here...</textarea>

  </fieldset>

  <fieldset class="bcls-fieldset">
    <legend>Results</legend>

    <h3>CSV Data</h3>

    <p>Copy and paste the data below into a an empty text file, and save it with a .csv extension. You can then open the file to view it in your spreadsheet application.</p>
    <textarea id="csvData_display" class="bcls-code" style="height:30em;"></textarea>

    <h3>Results Table</h3>
    <table class="bcls-table">
      <caption class="bcls-caption--table">Unique Users Report</caption>
      <thead class="bcls-table__head">
        <tr>
          <th>Date</th>
          <th>Unique Users</th>
          <th>Video Views</th>
        </tr>
      </thead>
      <tbody id="results_table_body" class="bcls-table__body"></tbody>
    </table>

  </fieldset>
</section>

            
          
!
            
              /* * The body style is just for the
 * background color of the codepen.
 * Do not include in your code.
 */
body {
  background-color: #111;
  color: #f5f5f5;
  font-family: sans-serif;
  margin: 2em;
}
/*
 * Styles essential to the sample
 * are below
 */
.bcls-code {
  color: #111;
  font-family: "Source Code Pro", monospace;
  padding: 1em;
  width: 90%;
  min-height: 5em;
  background-color: #cfcfcf;
  font-size: 1rem;
}
.bcls-request {
  color: #111;
  font-family: "Source Code Pro", monospace;
  padding: .5rem;
  width: 90%;
  min-height: 1rem;
  background-color: #cfcfcf;
  font-size: 1rem;
}
.bcls-button {
  padding: 0.5em;
  background-color: #333;
  border: 1px yellow solid;
  border-radius: 0.5em;
  color: yellow;
  cursor: pointer;
}
fieldset {
  color: #64aab2;
  border: 1px #64aab2 solid;
  border-radius: 0.5em;
}
code {
  color: #e4b842;
  font-family: "Source Code Pro", monospace;
}
.bcls-table {
  border-collapse: collapse;
  border: 1px #64aab2 solid;
}

.bcls-table .bcls-table__head th {
  border: 1px #64aab2 solid;
  padding: 0.5em;
}
.bcls-table .bcls-table__body td {
  border: 1px #64aab2 solid;
  padding: 0.5em;
}

            
          
!
            
              var BCLS = (function(window, document, rome) {
  var account_id,
    client_id,
    client_secret,
    // api stuff
    proxyURL = 'https://solutions.brightcove.com/bcls/bcls-proxy/bcls-proxy-v2.php',
    baseURL = 'https://analytics.api.brightcove.com/v1/data?accounts=',
    itemsArray = [],
    csvData,
    // elements
    account_id_input = document.getElementById('account_id'),
    client_id_input = document.getElementById('client_id'),
    client_secret_input = document.getElementById('client_secret'),
    fromDate = document.getElementById('fromDate'),
    toDate = document.getElementById('toDate'),
    makeReport = document.getElementById('makeReport'),
    csvData_display = document.getElementById('csvData_display'),
    results_table_body = document.getElementById('results_table_body'),
    apiRequest = document.getElementById('apiRequest'),
    apiResponse = document.getElementById('apiResponse'),
    fromDateValue,
    toDateValue,
    dayMS = 86400000,
    defaultFromDate = new Date(new Date() - 30 * dayMS);
  // date pickers
  rome(fromDate, {inputFormat:'YYYY-MM-DD', initialValue:getIsoDate(defaultFromDate), time: false});
  rome(toDate, {inputFormat:'YYYY-MM-DD', initialValue:getIsoDate(new Date()), time: false});

  /**
   * get the date part of an ISO date for a JavaScript date
   * @param  {date}   d A JavaScript date
   * @return {string}     The date part of the ISO string, e.g. 2019-01-01
   */
  function getIsoDate(d) {
    var isoString = d.toISOString();
    return isoString.substring(0, isoString.indexOf('T'));
  }


  /**
   * gets account info from inputs; if none, uses default account
   */
  function getAccountInfo() {
    account_id = account_id_input.value;
    client_id = client_id_input.value;
    client_secret = client_secret_input.value;
    // only use entered account id if client id and secret are entered also
    if (client_id.length > 0 && client_secret.length > 0) {
      if (account_id.length > 0) {
        account_id = account_id_input.value;
      } else {
        window.alert('To use your own account, you must specify an account id, and client id, and a client secret - since at least one of these is missing, a sample account will be used');
        client_id = null;
        client_secret = null;
        account_id = '1752604059001';
      }
    } else {
      account_id = '1752604059001';
    }
  }

  /**
   * creates the HTML table body for the display of results
   * @param {object} response the API response (parsed)
   */
  function createReportTable(response) {
    var iMax = response.items.length,
      i,
      item,
      row,
      td1,
      td2,
      td3;
    for (i = 0; i < iMax; i++) {
      item = response.items[i];
      row = results_table_body.insertRow();
      td1 = row.insertCell();
      td2 = row.insertCell();
      td3 = row.insertCell();
      td1.textContent = item.date;
      td2.textContent = item.daily_unique_viewers;
      td3.textContent = item.video_view;
    }
  }

  /**
   * createRequest sets up requests, send them to makeRequest(), and handles responses
   * @param  {string} type the request type
   */
  function createRequest(type) {
    var options = {},
      proxyURL = 'https://solutions.brightcove.com/bcls/bcls-proxy/bcls-proxy-v2.php';

    // set credentials
    // assumes input fields with ids: account_id, client_id, and client_secret
    if (document.getElementById('client_id').value.length > 0 && document.getElementById('client_secret').value.length > 0) {
      options.client_id = client_id;
      options.client_secret = client_secret;
    }
    options.requestType = 'GET';
    options.proxyURL = proxyURL;
    options.url = baseURL + account_id + '&dimensions=date&limit=all&fields=video_view,daily_unique_viewers&from=' + fromDateValue + '&to=' + toDateValue;

    switch (type) {
      case 'getJSON':
        apiRequest.textContent = options.url;
        makeRequest(options, function(response) {
          response = JSON.parse(response);
          apiResponse.textContent = JSON.stringify(response, null, 2);
          createReportTable(response);
          // now get the csv version
          createRequest('getCSV');
        });
        break;
      case 'getCSV':
        options.url += '&format=csv';
        apiRequest.textContent = options.url;
        makeRequest(options, function(response) {
          apiResponse.textContent = response;
          csvData_display.textContent = response;
        });
        break;

        // additional cases
      default:
        console.log('Should not be getting to the default case - bad request type sent');
        break;
    }
  }

  /**
   * send API request to the proxy
   * @param  {Object} options for the request
   * @param  {String} options.url the full API request URL
   * @param  {String="GET","POST","PATCH","PUT","DELETE"} requestData [options.requestType="GET"] HTTP type for the request
   * @param  {String} options.proxyURL proxyURL to send the request to
   * @param  {String} options.client_id client id for the account (default is in the proxy)
   * @param  {String} options.client_secret client secret for the account (default is in the proxy)
   * @param  {JSON} [options.requestBody] Data to be sent in the request body in the form of a JSON string
   * @param  {Function} [callback] callback function that will process the response
   */
  function makeRequest(options, callback) {
    var httpRequest = new XMLHttpRequest(),
      response,
      requestParams,
      dataString,
      proxyURL = options.proxyURL,
      // response handler
      getResponse = function() {
        try {
          if (httpRequest.readyState === 4) {
            if (httpRequest.status >= 200 && httpRequest.status < 300) {
              response = httpRequest.responseText;
              // return the response
              callback(response);
            } else {
              alert('There was a problem with the request. Request returned ' + httpRequest.status);
            }
          }
        } catch (e) {
          alert('Caught Exception: ' + e);
        }
      };
    /**
     * set up request data
     * the proxy used here takes the following request body:
     * JSON.strinify(options)
     */
    // set response handler
    httpRequest.onreadystatechange = getResponse;
    // open the request
    httpRequest.open('POST', proxyURL);
    // set headers if there is a set header line, remove it
    // open and send request
    httpRequest.send(JSON.stringify(options));
  }

  function init() {
    // event listeners
    csvData_display.addEventListener('click', function() {
      this.select();
    });
    // get initial account info
    getAccountInfo();
  }

  // button event handlers
  makeReport.addEventListener('click', function() {
    // get the inputs
    getAccountInfo();
    // get date range or default values
    fromDateValue = rome(fromDate).getDate();
    fromDateValue = getIsoDate(fromDateValue);
    toDateValue = rome(toDate).getDate();
    toDateValue = getIsoDate(toDateValue);
    createRequest('getJSON');
  });

  init();

})(window, document, rome);

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console