# Castlabs Web Player with Nowtilus SSAI

### **Step 1: Add** the MediaMelonPlayer SDK <a href="#step-1-add-mediamelon-smartstreaming-sdk-hardbreak" id="step-1-add-mediamelon-smartstreaming-sdk-hardbreak"></a>

Include the following import line to the web page in the start

```javascript
  <script type="text/javascript" src="https://PATH_TO_MEDIAMELON_PLAYER_SDK/mmsmartstreaming_castlabsplayer.min.js"></script>
```

### **Step2: Network call to fetch the Media and Vast urls** <a href="#step-2-register-and-initialize-mediamelon-sdk" id="step-2-register-and-initialize-mediamelon-sdk"></a>

Make a post network call to the channel URL and fetch the Media and Vast urls as shown in the below code snippet.

```javascript

      let NowtilusSSAIURL = "https://live.serverside.ai/ad-aggregation-service/mrss/channel/4c84556b-58e1-4d1f-b9bd-dd3241b7b1c2";
      let xhttp = new XMLHttpRequest();
      let mediaURL = "", vastURL = "", timelineArrayVOD = [];
      let isLive = false;


      if (isLive) {
        var dataSrc = ""
        let xhttp1 = new XMLHttpRequest();
        xhttp1.open("GET", "http://ssai.romeo.a1.net/abstractor/channel/1269/playoutUri/hls-default/HD?tls=true", true);
        xhttp1.setRequestHeader("x-account-api-key", "HSBY9-94ECY-20ECY-YWSE5-1WFE0");
        xhttp1.setRequestHeader("x-forwarded-for", "52.4.140.117");
        xhttp1.send();
        xhttp1.onreadystatechange = function () {
          if (this.readyState == 4 && this.status == 200) {
            let data = JSON.parse(this.response);
            dataSrc = data['data'];
          }
        };

        setTimeout(function () {
          let xhttp = new XMLHttpRequest();
          xhttp.open("POST", "https://ssaipre.serverside.ai/a1mm/live/1269", true);
          xhttp.setRequestHeader("Content-Type", "application/json");
          xhttp.setRequestHeader("x-forwarded-for", "52.4.140.117");

          let JSON_obj = {
            "data": dataSrc,
            "adServer": {
              "accountCode": "13625",
              "profileId": "13627",
              "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36"
            }
          };

          xhttp.send(JSON.stringify(JSON_obj));
          xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
              let data = JSON.parse(this.response);
              mediaURL = data.data.split("vast-data=")[0]
              mediaURL = mediaURL.substring(0, mediaURL.length - 1);
              vastURL = atob(data.data.split("vast-data=")[1].split("&token=")[0]);

            }
          };
        }, 1000);
      }
      else {
        xhttp.open("POST", NowtilusSSAIURL, true);
        xhttp.setRequestHeader("api-key", "79a8aff3-f3ec-4b1d-8c21-2074a4cc5b7b");
        xhttp.setRequestHeader("Content-Type", "application/json");
        xhttp.setRequestHeader("User-Agent", "Mozilla/5.0%20(Linux;%20Android%208.1.0;%20CPH1809)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/79.0.3945.93%20Mobile%20Safari/537.36");
        xhttp.setRequestHeader("Authorization", "Basic bm93dGlsdXM6bm93dGlsdXM=");

        var data = `{
      "url": "https://serversideai.blob.core.windows.net/agsmrss/serverside/serverside_mrss_preroll_midroll.mrss",
      "context": "web",
      "ifa": "ifa",
        "deliverytypes": [
        "hls"
        ]
    }`;
        xhttp.onreadystatechange = function () {
          if (this.readyState == 4 && this.status == 200) {
            let data = JSON.parse(this.response);
            mediaURL = data['hls'].url;
            timelineArrayVOD = data['hls'].clips;

          }
        };
        xhttp.send(data);
      }
```

### **Step 3: Register and Initialize** the MediaMelon Player SDK <a href="#step-2-register-and-initialize-mediamelon-sdk" id="step-2-register-and-initialize-mediamelon-sdk"></a>

{% hint style="info" %}
\<customer\_id> is your MediaMelon-assigned Customer ID. If you do not know your Customer ID contact MediaMelon at [support@mediamelon.com](http://40mediamelon.com/)
{% endhint %}

After the player instance has been created, create a new Plugin object, register, report player Info and then initialize the plugin as shown below:

{% hint style="info" %}
**Note:**

Please provide the exact correct details in all fields like CUSTOMER\_ID, ASSET\_ID, ASSET\_TITLE, VIDEO\_ID, PLAYER\_BRAND, PLAYER\_MODEL, PLAYER\_VERSION, PLAYER\_NAME, DOMAIN\_NAME, SUBSCRIBER\_ID, SUBSCRIBER\_TYPE & SUBSCRIBER\_TAG.\
\
This data helps in debugging through MediaMelon SmartSight if anything goes wrong.
{% endhint %}

<pre class="language-javascript"><code class="lang-javascript">    let mmCastlabsPlugin = CastlabsMMSSJSIntgr();
    if (mmCastlabsPlugin.getRegistrationStatus() === false) {
      // Register with Mediamelon SDK
      // Change the required fields here
      mmCastlabsPlugin.registerMMSmartStreaming("castlabs", "CUSTOMER_ID",
        "SUBSCRIBER_ID",
        "DOMAIN_NAME",
        "SUBSCRIBER_TYPE",
        "SUBSCRIBER_TAG");
      mmCastlabsPlugin.reportPlayerInfo("PLAYER_BRAND", "PLAYER_MODEL", 'PLAYER_VERSION');
      mmCastlabsPlugin.enableLogTrace(false);
    }
<strong>    var mmVideoAssetInfo = {
</strong>      "assetName": "ASSET_NAME",
      "assetId": "ASSET_ID",
      "videoId": "VIDEO_ID",
      "contentType": "CONTENT_TYPE",
      "genre": "GENRE",
      "drmProtection": "DRM_PROTECTION",
      "episodeNumber": "EPISODE_NUMBER",
      "season": "SEASON",
      "seriesTitle": "SERIES_TITLE",
      "videoType": "VIDEO_TYPE",
      "customTags": {
        "key1": "VALUE_STRING1",
        "key2": "VALUE_STRING2"
      }
    };
    
    // Initializing the Nowtilus plugn
    var mmSSAITestPlugin = new mmNowtilusSSAIPlugin(player);
    
    setTimeout(function () {
      var nowtilusConfig = {
        isLive: isLive,
        streamType: 'dash',  //'hls' for hls stream
        apiKey: "23141f0f-24d7-4e77-9ba8-907d5d42bdc6",
        url: mediaURL,
        context: 'web',
        ifa: 'ifa',
        enablePolling: true,
      };

      mmSSAITestPlugin.setup(mediaURL, vastURL, timelineArrayVOD, nowtilusConfig);
      mmCastlabsPlugin.initialize(player, mediaURL, mmVideoAssetInfo, mmSSAITestPlugin, isLive);
      player.load(mediaURL);
  
    }, 4000);
</code></pre>

### Step 4: Listen to Ad Callback Events for Disabling Player Controls <a href="#vr-step-5-registering-for-ad-events-for-disabling-player-controls" id="vr-step-5-registering-for-ad-events-for-disabling-player-controls"></a>

Listen to the Ad callbacks provided by MediaMelon SDK for disabling the player controls during the Ad playback and can be enabled back when the Ad playback ends.

```javascript
NowtilusAdPlugin.addListener('onCueTimelineAdded', function (adinfo, adTimeline) {
        // adTimeline is an Array of adinfo objects. This contains details of all the Ads from upcoming Ad break.
        console.log("onCueTimelineAdded callback");
  });
NowtilusAdPlugin.addListener('onCueTimelineEnter', function (adinfo) {
        console.log("onCueTimelineEnter callback");
});
NowtilusAdPlugin.addListener('impression', function (adinfo) {
        console.log("AD Impression callback");
});
NowtilusAdPlugin.addListener('start', function (adinfo) {
        console.log("AD start callback");
});
NowtilusAdPlugin.addListener('firstQuartile', function (adinfo) {
        console.log("AD FirstQuartile callback");
});
NowtilusAdPlugin.addListener('midpoint', function (adinfo) {
        console.log("AD Midpoint callback");
});
NowtilusAdPlugin.addListener('thirdQuartile', function (adinfo) {
        console.log("AD ThirdQuartile callback");
});
NowtilusAdPlugin.addListener('complete', function (adinfo) {
        console.log("AD Complete callback");
});
NowtilusAdPlugin.addListener('onCueTimelineExit', function (adinfo) {
        console.log("onCueTimelineExit callback");
});
```

### API's Provided by MediaMelon SDK Plugin

<pre class="language-javascript"><code class="lang-javascript">// Registering MediaMelon SDK
mmCastlabsPlugin.registerMMSmartStreaming("PLAYER_NAME", "CUSTOMER_ID", "SUBSCRIBER_ID", "DOMAIN_NAME", "SUBSCRIBER_TYPE", "SUBSCRIBER_TAG");

// Checking MediaMelon SDK Registration Status. This API returns a boolean value where, 
// true -> MediaMelon SDK Registration is Completed
// false -> MediaMelon SDK Registration is Pending
mmCastlabsPlugin.getRegistrationStatus()

// Reporting Player Information
mmCastlabsPlugin.reportPlayerInfo("PLAYER_BRAND", "PLAYER_MODEL", 'PLAYER_VERSION');

// Initializing MediaMelon SDK
mmCastlabsPlugin.initialize(&#x3C;PLAYER_OBJECT>, "MEDIA_URL", &#x3C;MM_VIDEO_ASSET_INFO>, &#x3C;MM_SSAI_PLUGIN_OBJECT>);

// Enable or Disable Log Trace. It takes a boolean value as an input parameter.
<strong>// true -> Enabling Log Trace
</strong>// false -> Disabling Log Trace
mmCastlabsPlugin.enableLogTrace(false);

// Reporting Current Player State as Stopped
mmCastlabsPlugin.reportPlayerStopped();

// Updating Subscriber Details
mmCastlabsPlugin.updateSubscriber("SUBSCRIBER_ID", "SUBSCRIBER_TYPE", "SUBSCRIBER_TAG");

// Reporting Custom Metadata in a KEY &#x26; VALUE format
mmCastlabsPlugin.reportCustomMetadata("KEY", "VALUE_STRING");

// Shutting Down the MediaMelon SDK
mmCastlabsPlugin.closeMediaMelonSDK();
</code></pre>

| Variable         | Description                                                                                                                                                                          |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| PLAYER\_NAME     | String containing the Player Name.                                                                                                                                                   |
| CUSTOMER\_ID     | String containing your MediaMelon-assigned Customer ID.                                                                                                                              |
| SUBSCRIBER\_ID   | String containing your Subscriber’s ID. If you do not use subscriber IDs, enter null                                                                                                 |
| DOMAIN\_NAME     | String containing your section of your subscriber or assets. (Optional)                                                                                                              |
| SUBSCRIBER\_TYPE | String containing the Subscriber Type (e.g. “Free”, “Paid”). If you do not use subscriber types, enter null                                                                          |
| SUBSCRIBER\_TAG  | String containing an additional subscriber-specific information. This is sent in clear (not hashed) to SmartSight and it is advised to not send sensitive information in this field. |
| ASSET\_ID        | String containing Asset Id.                                                                                                                                                          |
| ASSET\_NAME      | String containing Asset Name.                                                                                                                                                        |
| VIDEO\_ID        | String containing your video’s ID. If you do not use videos IDs, enter null.                                                                                                         |
| COTENT\_TYPE     | String containing type of the Content. For example - "Movie", "Special", "Clip", "Scene Epis Lifts".                                                                                 |
| GENRE            | String containing Genre of the content. For example - "Comedy", "Horror".                                                                                                            |
| DRM\_PROTECTION  | Widevine, Fairplay, Playready etc. Unknown means content is protected, but protection type is unknown. For clear contents, do not set this field                                     |
| EPISODE\_NUMBER  | String containing sequence number of the Episode.                                                                                                                                    |
| SEASON           | String containing the Season. For example - "Season1".                                                                                                                               |
| SERIES\_TITLE    | String containing Title of the Series.                                                                                                                                               |
| VIDEO\_TYPE      | String containing Video Type. For example - "LIVE", "VOD".                                                                                                                           |
| CUSTOM\_TAGS     | Extra custom metadata can be added here if required. If extra metadata is not required, enter null.                                                                                  |
| PLAYER\_BRAND    | String containing Player Brand.                                                                                                                                                      |
| PLAYER\_MODEL    | String containing Player Model. For example - This could be a variant of player. Say name of third party player used by organisation. Or any human readable name of the player.      |
| PLAYER\_VERSION  | String containing Player Version.                                                                                                                                                    |
