In this tutorial, we will describe step by step process of application creation for LaMetric that will use OAuth2 authorization, user options and will display YouTube channel subscribers.

Requirements:

  • Google account
  • LaMetric application (should be created on developer.lametric.com)
  • Simple Web service (find implementation below)

 As a result, we should get YouTube channel subscriptions number on your LaMetric:


Architecture

The whole system will consist of these parts:

  • Web Service – will query YouTube API to get some numbers
  • LaMetric Application – will be a client for the Web Service.
In general, LaMetric application will be querying Web Service every minute for new data. Web Service in turn, will query YouTube and respond with JSON in a specific format. 

Let's start with Web Service.


Web Service

Let’s design our API. We want to have single custom API method to get our subscriber count.


Method

API

Parameters

Description

GET

/youtube/channelSubscriberCount

channelId

Should return number of subscribers for specific channel.


Request

GET: /youtube/channelSubscriberCount?channelId=<channelId>

Header

Authorization:bearer <ACCESS_TOKEN>

Accept: application/json


Response

Status: 200,

Body:

  

{
    frames: [
        {
            "index":"0",
            "icon":"i280",
            "text":"30642", 
        }
    ]
}

  

If YouTube returns any other status code – it has to be returned to LaMetric as is, in order to be properly handled. For example – in case of access token expiration (status 401) – LaMetric will try to refresh it.

 

Implementation

You can create Web service using any technology you are familiar with, such as NodeJS, Python, .Net, PHP, etc. For this demo we are going to use NodeJS + SailsJS.

Requirements:

Steps:

  1. Install NodeJS (https://nodejs.org/en/download/) and SailsJS (http://sailsjs.org/get-started)
  2. Create new SailsJS project. To do that execute these commands:
  • $ sails new youtube_subscribers
  • $ cd youtube_subscribers
  • $ sails generate api youtube
  • $ sails lift

Now you should have your API up and running on your machine at http://localhost:1337/youtube. It should respond with empty JSON array.


To get YouTube channel subscriber count we have to use YouTube Data API v3 (https://developers.google.com/youtube/v3/docs/channels/list).

When you do GET request to https://www.googleapis.com/youtube/v3/channels?part=statistics&id=<channel_id>&key=<your app key> you should get response like this:

Status: 200

Body:  

{
    "kind": "youtube#channelListResponse",
    "etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/RqmnLwyh4I_bHRJScqyMRhkhFZ8\"",
    "pageInfo": {
        "totalResults": 1,
        "resultsPerPage": 1
    },
    "items": [
        {
            "kind": "youtube#channel",
            "etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/ncgZmQl1DcCk6CvDxiqhxmKCOEY\"",
            "id": "UCMt7hn5WP-MWrRucZqzmWmQ",
            "statistics": {
                "viewCount": "0",
                "commentCount": "0",
                "subscriberCount": "1",
                "hiddenSubscriberCount": false,
                "videoCount": "1"
            }
        }
    ]
}

   

As you can see we will have to get our “subscriberCount” attribute of the YouTube response and pass it to LaMetric. Of course, call to that URL has to be authenticated using OAuth2 with proper permission requested. This is done by LaMetric, so we will just take authorisation header from request sent by LaMetric and pass it to request that we do to YouTube API. Also you will have to know your App ID. To get one you should register your app at Google Developer Console.


Registering your app at Google

Steps:

  1. Go to Google Developer Console
  2. Create new project there (Choose Create new project… from the top drop down list)
  3. Enable YouTube Data API v3

  4. Create App Credentials






  5. Finally you have your Client ID and Client secret. Client ID is used in the Web service implementation (file /config/youtube_data.js) as well as in LaMetric application. We will get to this a little bit later.
Source Code

Lets do some coding stuff :)

/config/youtube_data.js
module.exports.youtubeDataV3 = {
baseUrl: 'https://www.googleapis.com/youtube/v3',
appId:'<your app id>'
};

/api/services/RequestService.js
var request = require('request');
module.exports = {
        /**
         * Method: getData
         * @return json
         * returns Response called API method
         */
        getData: function(url, header, queryParams, callback) {
                console.log("GET: ", url);
                console.log("QS: ", queryParams);
                console.log("Headers: ", header);
                
                request.get({
                        url: url,
                        qs: queryParams,
                        headers: header,
                        rejectUnauthorized: true,
                }, function(error, response, body) {
                        if (!error && response.statusCode == 200) {
                            try {
                                callback(null, response, JSON.parse(body));
                            } catch (err) {
                                callback(err, response);
                            }
                        } else {
                            callback(error, response, null);
                        }
                });
        }
}


/api/services/YoutubeService.js
/**
 * YoutubeService
 *
 * @description :: Server-side logic for managing youtubes
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
        /**
         * Method: getChannelSubscriberCount
         * @return json
         * returns Gets number of subscribers for channel
         */
        getChannelSubscriberCount: function(headers, parameters, callback) {
                var url = sails.config.youtubeDataV3.baseUrl + '/channels';
                var params = {
                	part:'statistics',
                	id:parameters.channelId
                };

                var postHeader={
                    'User-Agent': headers.host,
                    'Accept':'application/json',
                    'Authorization':headers.authorization // pass authorization header received in request
                };

                RequestService.getData(url, postHeader, params, callback);
        },
}


/api/controllers/YoutubeController.js

/**
 * YoutubeController
 *
 * @description :: Server-side logic for managing youtube
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
        /**
         * Method: channelSubscriberCount
         * @return json
         * returns Gets YouTube Channel subscriber count
         */
        channelSubscriberCount: function(req, res) {
                console.log("Headers: ", req.headers);
                console.log("Query Parameters: ", req.query);
                YoutubeService.getChannelSubscriberCount(req.headers, req.query, function(err, response, data) {
                        if (err || response.statusCode != 200) {
                            if (err) {
                                console.log(err);
                                return res.status(500).send(err)
                            } else {
                                return res.status(response.statusCode).send(response.body);
                            }
                        };
                        
                        // Building object for LaMetric. We will return it
                        var responseObj={};
                        responseObj.frames=[];
                        var frame = {
                            'index':0,
                            'text': '0',
                            'icon':'i280',
                        };

                        // Checking if we have required parameters passed to our API. 
                        if (req.query.channelId === '') {
                            // If no channel Id – displaying this text
                            frame.text = 'CHNL?'
                        } else {
                            // Getting subscriber count from YouTube Data API response.
                            frame.text = data.items[0].statistics.subscriberCount;                        
                        }

                        responseObj.frames.push(frame);

                        if (!data) {
                            console.log("Error: ", response.statusCode);
                            res.status(response.statusCode).send(response.body);
                        } else {
                            console.log("Response: ", responseObj);
                            return res.status(200).json(responseObj);
                        }
                })
        },
}

   

Starting Web Service

Now when the code is in place it is time to start our web service. At first, let's install some NodeJS dependencies:

# npm install request

And start Web service:

# sails lift

Web service should work on your computer at this point. To access it in your network you should know your computer’s IP address. LaMetric should access it on your local network just fine. But if you are planning to publish your app for everyone – please consider hosting your web service somewhere in the cloud. There are few free NodeJS hostings you can use (for example OpenShift – https://www.openshift.com/pricing/index.html).


LaMetric Application

Now it is time to create LaMetric app – a client for your web service.

Steps:

  1. Go to https://developer.lametric.com
  2. Create indicator app with single frame:

  3. Choose app type to be “Poll”
  4. Fill in your data URL and poll frequency
     
  5. Add OAuth2 authentication option

    OAuth2 type Google
    Client id <your client id>
    Client secret <your client secret>
    Auth URL https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent
    Redirect URI http://lametric.com/redirect
    Scope https://www.googleapis.com/auth/youtube.readonly
    Response type Code

    Access/Refresh token URL

    https://www.googleapis.com/oauth2/v4/token


  6. Add option for channel ID that we will be used in order to get subscribers

  7. Publish your app privately.

Results
Now it is time to see the results of our work! 
  1. Install the YouTube Subscribers app to your LaMetric (it should be already available in LaMetric Store privately for you). 
  2. Configure it to track some YouTube channel.

    (you can find youtube channel ID in your browser's address field)


    And here it is!


You can install and play with the app as it is available in the LaMetric Appstore.

Enjoy!