Keeping alive the messenger architecture on free heroku dynos

Heroku is a cloud application platform – a new way of building and deploying web apps and a PaaS service to host applications in various programming languages and frameworks on its cloud. The entire architecture behind the messengers has been written with nodejs and deployed to heroku as its production for one main reason which is that it provides a verified and signed SSL Certificate along with its deployment which is useful for facebook messenger integration of susi as well as useful for telegram to trigger webhooks on SSL.

A major problem with the dynos (apps deployment) is that for free users the deployment automatically goes to sleep if no one is using it for a short while and only wakes up when the endpoint is hit and also is available in a day for upto 18 hours. This could be problematic when the deployment is made, so the best way is to have maximum utilization of the resources and keep it awake as and when required. This was resolved with facebook messenger because of incoming event webhooks that are available which request the server to wake up in case they sleep but what about Slack ? The slack server doesn’t send a notification event to the server when a message is sent by a user mentioning susi which is just like every other user and can be added to a channel.

To fix this problem there are multiple approaches that we’ve taken, the first step is to ensure that every fixed time interval the server pings itself so that it’s kept alive. This is accomplished with this fraction of the code

setInterval(function() {
		http.get(heroku_deploy_url);
	}, 1800000); //pings the deployment url every 30 minutes

where the heroku_deploy_url is an environment variable that can be set by the user depending on the URL of the deployment.

Another option was to use the New Relic insights and their availability tracker to keep sending requests after every fixed interval of time and use it to keep the server alive. This can be accomplished by doing the following on the heroku toolbelt.

heroku addons:add newrelic:standard
heroku addons:open newrelic

then using the following ruby script and setting the PING_URL as heroku config:add PING_URL=http://longweburl.herokuapp.com

desc "Pings PING_URL to keep a dyno alive"
    task :dyno_ping do
      require "net/http"

      if ENV['PING_URL']
        uri = URI(ENV['PING_URL'])
        Net::HTTP.get_response(uri)
      end
    end

and then performing the execution of the task by doing

heroku addons:add scheduler:standard
heroku addons:open scheduler
rake dyno_ping

The last option was however to use the existing loklak.net server setup a cronjob on that to query the heroku instance periodically so that the instance quota doesn’t get over and at the same time has as much uptime as majorly required. The best option however would be to upgrade to a hobby plan and purchase a dyno to host the resource.

Keeping alive the messenger architecture on free heroku dynos

Setting up Susi for access from Telegram Messenger

Telegram is one of the popular applications for communication in the open source community and was one of the first apps to come out with end to encryption soon to be followed suit by whatsapp messenger and other messengers. Telegram is used by a large number of people and we the folks at loklak put on our thinking hats and decided why not provide susi’s capabilities to those using Telegram and the telegram integration to the ask susi messengers integration was born.

Consuming the Susi API with Telegram is fairly straightforward in telegram. The first step is the use of botfather in telegram ensures that the bots can be created with ease. So the first step is to login into telegram with your user account and search and talk to BotFather. Bot father would ask a few questions and then provide the required token. You need to save this token and the bot powered by susi is now available.

botfather1

botfather2

This sets up the bot and provides the token, the next step is to use the token and setup the way in which it responds. This was done by keeping the token as an environment variable

var telegramToken = process.env.TELEGRAM_ACCESS_TOKEN;

and continuing to build the response system around what should happen when a message event is received from telegram. To start the bot the standard entry to the bot happens using the /start message that’s sent to the telegram service.

bot.onText(/\/start/, function (msg, match) {
	var fromId = msg.from.id;
	var resp = 'Hi, I am Susi, You can ask me anything !';
	bot.sendMessage(fromId, resp);
});

This initiates the bot if it’s the first time a user is using the bot, here after every event is read and processed by susi and the response is returned

bot.on('message', function (msg) {
	var chatId = msg.chat.id;
	var queryUrl = 'http://loklak.org/api/susi.json?q='+encodeURI(msg.text);
	var message = '';
	// Wait until done and reply
	if (msg.text !== '/start') {
		request({
			url: queryUrl,
			json: true
		}, function (error, response, body) {
			if (!error && response.statusCode === 200) {
				message = body.answers[0].actions[0].expression;
				bot.sendMessage(chatId, message);
			} else {
				message = 'Oops, Looks like Susi is taking a break, She will be back soon';
				bot.sendMessage(chatId, message);
			}
		});
	}
});

Here’s how Susi’s capabilities are now available to all those users on telegram.

Setting up Susi for access from Telegram Messenger

Susi supports Map tiles

Susi chat client supports map tiles now. Try out the following query related to location and Susi responses with a internal map tile with the pin at the location.

Where is Singapore? 

Selection_310

You have internal zoom in and zoom out options for the map. It also provides you with a link to open street maps where you can get the whole view of the location. Other than the map tile it gives you information about the location’s population. Isn’t it awesome?

Implementation: Let’s get into the implementation part. There are multiple ways to display the map tiles. One way is we can use our own Loklak services for displaying the map. For example -> you can make a call to the /vis/map.png API for displaying the map. But the issue with this API is we cant dynamically zoom in or zoom out the map on the tile, which is moreover a static display. So to make it more interesting we used a js library called Leaflet, which provides interactive maps.

How is the data captured? Here is the sample response coming from the server.

Selection_307

This sample data which contains latitude, longitude, place and population helps us for drawing the map tiles.

  1. expression:“Berlin is a place with a population of 3426354. Here is a map: https://www.openstreetmap.org/#map=13/52.52436820069531/13.41053001275776”
  2. type:“answer”

The above two keys are under the actions object providing the us the answer along with the URL where it is linkified.

How is the map captured? First we included the following required library files.

<script src=”https://npmcdn.com/[email protected]/dist/leaflet.js”></script>

<link rel=”stylesheet” href=”https://npmcdn.com/[email protected]/dist/leaflet.css” />

Selection_312

The JSON response is parsed and the co ordinates (lat, lon) are captured. The variable type mapType initialized.

Selection_313

PS: The co ordinates are passed into the response, for telling the html that ‘hey the map is coming in the response!’ so that it prepares it’s space for the map. Here’s the html’s job. (Handlebars)

Selection_314

The extra div for the maps are loaded when intimated about the map.

Selection_316

When the mapType is set to true the drawMap method is called which initializes the id for the the html and paints the map tile to it. The object has attributes like maxZoom levels, Map marker and it’s tooltip on the map. And that’s how the map tiles are formed.

 

 

 

Susi supports Map tiles

Publicising your Slack Bot through Slack Apps + the Add to Slack button

In my previous blog posts on Slack bots, I spoke about making bots, both using a simple script, and using incoming webhooks. We are now well versed with how to code up a slack bot and code it according to our needs.

Now that our Slack bot is made. How do we get it through to everyone?

Slack offers an amazing feature for the same, the Add to Slack button. Using this button, other teams can simply add your bot to them, and this is one of the best ways of publicising, because this button can be kept anywhere: your website, your README.md on github, a blog post etc.

Add to Slack, however works with OAuth, so that only authorised teams can take in your bot. Also, for distributing your bot, you will have to package it into a Slack app. So, let’s get started!

First off, we’ll make a Slack app:

1. Login into your team on Slack.
2. Go to the Apps page here and click on “Create an App”.

3. Fill out the relevant details for your app. You should especially fill out the redirect_uri (it’s not compulsory but you’ll have to fill it sometime) since it is needed for OAuth (when other users use your bot). Once form filled, click on Add App.

4. Go to the main page of your app, and under Bot Integrations, add your bot (keep the name as @susi, or whatever you like. You’ll have to change the bot name then in the code).

5. Go to App Credentials, and save the client_id and the client_secret for reference. We need it for OAuth.

Don’t worry, we’ll handle the redirect_uri in a short while!

So the flow of this goes as follows:

1. When a team clicks on “Add to Slack” button, they are led to a page, where they have to verify that a bot is being added to their team. Once they have verified, you click on “Authorize”.

2. When one clicks on Authorize, Slack generates a code, and appends it to the redirect_uri as a GET parameter, and leads you there.

3. Your redirect_uri needs to handle this code, and then send the client_secret, client_id and this code as GET parameters to http://slack.com/api/oauth.access, so that your OAuth request is verified.

4. Once request is verified and the parameters match, the bot is successfully deployed onto your team. Additionally, a JSON is returned, specifying your access_token for the bot you just deployed, as well as the incoming webhook URL (incase you have incoming webhook in your code). You need to now use this very access token and the webhook URL to control your bot.

Let’s get started on implementing this then.

1. We first go to the Slack Button page. In the bottom of the page under the section “Add to Slack Button”, there is a box, where there’s a custom url so that you can add the bot to your website etc (where people will click on it). There are three checkboxes there as you can see. Check whichever one you need for your bot:

Screen Shot 2016-08-29 at 6.37.26 PM

2. Once you have selected this, you can embed this into your website / README file. That’s half the job done!

Now let’s dive into the code. We need to take in the code that’s sent as a GET parameter to our redirect_uri. Once we get this code, we need to send in a GET request to http://slack.com/api/oauth.access with the client_id, client_secret and this code. If the bot is approved, we take up the webhook url / bot token and use it for the deployed bot so that it runs properly.

Here, the redirect_uri I’ll use is the Slack deployment URL I have on Heroku (http://asksusisunode.herokuapp.com). I’ll just create a path on Express, named ‘/slackbot’, and get started from there. The entire process starts when you get the code as a GET parameter on the redirect_uri. So do the following:

1. Go to your Apps page on Slack, under App credentials, add http://yourherokuurl.com/slackbot (or obviously any other URL you have) as the redirect_uri. I used http://asksusisunode.herokuapp.com/slackbot as the redirect_uri.

2. Let’s dive into the code now. Below is the final code that handles the Add to Slack button:


'use strict';
/* global require, process, console */

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var SlackBot = require('slackbots');
var http = require("http");
var Slack = require('node-slackr')
var app = express();
var custom_slack_token;
var slack_token = process.env.SLACK_TOKEN
var payload;
var payload_url = process.env.PAYLOAD_URL //this is just the webhook URL
var custom_payload_url;
var slack; 

var slack_code;
var client_id = process.env.CLIENT_ID;
var client_secret = process.env.CLIENT_SECRET;

app.set('port', (process.env.PORT || 5000));

app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json());

app.get('/', function (req, res) {
	res.send('Susi says Hello.');
});

app.get('/slackbot', function(req, res) {
	slack_code = req.param('code'); //getting the code GET parameter
	var queryurl = 'http://slack.com/api/oauth.access?client_id='+client_id+'&client_secret='+client_secret+'&code='+slack_code;
	console.log(queryurl);
	request(queryurl, {json:true}, function(error, response, body) { // we get a JSON response
		if(!error && response.statusCode == 200 && body.ok == 'true'){ //i.e if bot has been installed

//take in the slack token and webhook url
			custom_slack_token = body.bot.bot_access_token;
			custom_payload_url = body.incoming_webhook.url;
			console.log(body);
			console.log(slack_token);
			res.send('Susi has been installed to your team!');
		} else{
			res.send('Could not install');
		}
	});
});

function slackbot(){
	
	setInterval(function() {
		http.get("http://asksusisunode.herokuapp.com");
	}, 1800000); 

	if (custom_slack_token && custom_payload_url){
		slack_token = custom_slack_token;
		payload_url = custom_payload_url;
	}
	var slack_bot = new SlackBot({
		token: slack_token, 
		name: 'susi'
	})

	slack = new Slack(payload_url);

	slack_bot.on('message', function(data){
		var slackdata = data;
		var msg, channel, output, user;
		if(Object.keys(slackdata).length > 0){
			if('text' in slackdata && slackdata['username'] != 'susi'){
				msg = data['text'];
				channel = data['channel']
			}
			else {
				msg = null;
				channel = null;
			}
		}
		if(msg != null && channel !=null){
			var botid = '<@U1UK6DANT>' //need to change
			if (msg.split(" ")[0] != botid){
			//do nothing
		} else{
			var apiurl = 'http://loklak.org/api/susi.json?q=' + msg;
			var payload;
			request(apiurl, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var data = JSON.parse(body);
					if(data.answers[0].actions.length == 1){
						var susiresponse = data.answers[0].actions[0].expression;
						payload = {
							text: susiresponse,
							channel: channel
						}
						slack.notify(payload)

					} else if(data.answers[0].actions.length == 2 && data.answers[0].actions[1].type == "table"){
						payload = {
							text: data.answers[0].actions[0].expression + " (" + data.answers[0].data.length + " results)",
							channel: channel
						}
						slack.notify(payload)
						for(var i = 0; i < data.answers[0].data.length; ++i){
							var response = data.answers[0].data[i];
							var ansstring = "";
							for(var resp in response){
								ansstring += (resp + ": " + response[resp] + ", ");
							}
							payload = {
								text: ansstring,
								channel: channel
							}
							slack.notify(payload);
						}
					}
				}
			});
		}
	}
});
}

// Getting Susi up and running.
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
	slackbot();
});

There’s just one small shortcoming: the bot id used above won’t be the same for the deployed bot, so there can be cases where you message the bot but it does not reply. So we need to actually use the RTM API to figure out the bot id directly. We’re in the process of fixing it. But the bot will definitely be installed into your team, just that in some cases it won’t message and will stay “Away”.

See? It was as simple as adding another path in Express, and the awesome Requests package does the rest. Your bot will successfully be added to your team as a result, and anyone can use it. 🙂

Apart from publicising using the Add to Slack button, additionally, you can also publicise your app on the Slack Apps directory by going here and filling out the form.

So now we know how to make a Slack bot from scratch, from two different methods, and how to effectively publicise it. This is another great way by which Susi will be publicised to everyone and more people can use it. Amazing, right?

By the way, please go to https://github.com/fossasia/asksusi_messengers and add more bots for Susi there. We wish to add Susi on as many platforms as possible. We really value your contributions 🙂

So that’s it for today! Feedback is welcome as always 🙂 See you later!

Publicising your Slack Bot through Slack Apps + the Add to Slack button

Making Slack Chatbots using Incoming Webhooks + The Idling problem

The last time I spoke about Chatbots, I spoke about the need of increasing Susi’s reach, how Slack is a great platform because of how it works within teams, and how to make a Slack bot yourself.

However, if you see the code snippet I posted in that blog post, you’ll see that the Slack bot I have is just a Python script, while the rest of the index.js code (which contains the Messenger and Telegram bots) is an Express application. We are basically just using a package (slackbots, if you remember), and it simply takes in your Slack token and POSTs to the Slack interface. Also, that is a custom bot, it will only be in use for us right now, we need to distribute it (which we do using Slack apps, we’ll talk about that later).

Today, I’ll be describing another method of making Slackbots: using Incoming Webhooks.

Incoming Webhook is a way by which you don’t directly POST to the Slack interface, but you POST to a webhook generated by Slack. It is a very convenient way of posting messages from external sources into Slack. Moreover, when you distribute your Slack bot, you can distribute your Webhook separately so that your reach can increase more (we’ll talk about distributions and OAuth in the next blog post). Incoming webhooks are seamlessly integrated within your Slack apps, so that your Slack bot can be distributed efficiently.

So let’s get started. To create an Incoming webhook integration:

1. Go to the Incoming Webhook Integration page here.

2. Fill in the details and select the channel you wish to post to.

3. Save the webhook URL for reference. We’ll need it.

Incoming Webhooks work with a payload. A payload is a JSON which contains all the information of the message (text, emojis, files etc). A normal payload looks like:

payload={"text":"This is a line of text.\nAnd this is another one."}

Now all we need to do is POST our message, AS a payload, to this URL, instead of directly posting to Slack. For easily handling payloads, we use a library named node-slackr. You can install it as follows:

npm install --save node-slackr

To post a payload to the URL, we first instantiate the node-slackr object using our webhook URL:

var slack = new Slack(webhook_url);

When we have the payload ready, all we need to POST to the webhook is simply do:

slack.notify(payload);

So here’s the final modified code that’s used for making bots using incoming webhooks. We just make a few changes to our original bot code in the last post on Slack bots on this blog:


'use strict';
/* global require, process, console */

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var SlackBot = require('slackbots');
var Slack = require('node-slackr')
var app = express();
var slack_token = process.env.SLACK_TOKEN
var webhook_url = process.env.WEBHOOK_URL
var heroku_url = process.env.HEROKU_URL
var slack; 

app.set('port', (process.env.PORT || 5000));

app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json());

app.get('/', function (req, res) {
	res.send('Susi says Hello.');
});

function slackbot(){
	
	setInterval(function() {
		http.get(heroku_url);
	}, 1800000); 

	var slack_bot = new SlackBot({
		token: slack_token, 
		name: 'susi'
	})

	slack = new Slack(payload_url);

	slack_bot.on('message', function(data){
		var slackdata = data;
		var msg, channel, output, user;
		if(Object.keys(slackdata).length > 0){
			if('text' in slackdata && slackdata['username'] != 'susi'){
				msg = data['text'];
				channel = data['channel']
			}
			else {
				msg = null;
				channel = null;
			}
		}
		if(msg != null && channel !=null){
			var botid = ':' 
			if (msg.split(" ")[0] != botid){
			//do nothing
		} else{
			var apiurl = 'http://loklak.org/api/susi.json?q=' + msg;
			var payload;
			request(apiurl, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var data = JSON.parse(body);
					if(data.answers[0].actions.length == 1){
						var susiresponse = data.answers[0].actions[0].expression;
						payload = {
							text: susiresponse,
							channel: channel
						}
						slack.notify(payload)

					} else if(data.answers[0].actions.length == 2 && data.answers[0].actions[1].type == "table"){
						payload = {
							text: data.answers[0].actions[0].expression + " (" + data.answers[0].data.length + " results)",
							channel: channel
						}
						slack.notify(payload)
						for(var i = 0; i < data.answers[0].data.length; ++i){
							var response = data.answers[0].data[i];
							var ansstring = "";
							for(var resp in response){
								ansstring += (resp + ": " + response[resp] + ", ");
							}
							payload = {
								text: ansstring,
								channel: channel
							}
							slack.notify(payload);
						}
					}
				}
			});
		}
	}
});
}

// Getting Susi up and running.
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
	slackbot();
});

All we did is set the webhook url as an environment variable, and used that, and just did slack.notify. Also, I encapsulated the function inside app.listen so that it runs up as soon as the app starts and stays alive.

But here comes another problem: We used heroku dynos for deployment. Heroku dynos have a sleep period of 6 hours. In those 6 hours, the bot would just be idle and would not work. We wish to circumvent this.

There are three ways of doing so. One way is to install the newrelic plugin of Heroku and using it (you can read more about it here). The second way is to simply use Kaffeine so that your heroku url is pinged every 30 minutes and the bot stays alive.

Or you can programatically solve it as well. Look at the code snippet above and notice:


setInterval(function() {
		http.get(heroku_url);
	}, 1800000); 

We’re basically pinging the Heroku URL (again stored as env var) every 1800000 milliseconds, i.e 30 minutes. This is a more convenient approach to solve this problem of idling too.

So now we know how to make our bot using two different methods, and how to solve the idling problem. To get this full circle, in the next blog post, I will talk about distribution of your bot, and how people can know about it. Feedback is welcome as always 🙂

Making Slack Chatbots using Incoming Webhooks + The Idling problem

Monetisation of Susi using the Amazon Product API (Part 2)

So in my previous blog post, I covered about the semantics of the Amazon Product Advertising API, and how does the monetisation work. Today, let’s jump into the code and the relevance with Susi.

We have seen that the Amazon Product Advertising API is a SOAP API. The query of the SOAP API access goes like this:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[AWS Access Key ID]&AssociateTag=[Associate ID]&Operation=ItemSearch&Keywords=the%20hunger%20games&SearchIndex=Books&Timestamp=[YYYY-MM-DDThh:mm:ssZ]&Signature=[Request Signature]

We supply to it the Operation (ItemSearch, ItemLookup etc, you can have the full list here), the Keywords to look for (could be a keyword or an ASIN (if it is ItemLookup i.e search by ID) and the Timestamp, Signature (base 64 Hmac) and of course the tags. Now we need to implement this in a real Java program. But the SOAP nature of the API could obviously cause some inconveniences.

Thankfully, Amazon made up a REST API code snippet which people can directly use. It takes in the URL as mentioned above, generates the timestamp, and signs the query with the Access ID, Associate Tag and the other params in the Hmac algorithm (which uses Base64). Here is the code: (SignedRequestsHelper.java)


/**********************************************************************************************
 * Copyright 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 
 * except in compliance with the License. A copy of the License is located at
 *
 *       http://aws.amazon.com/apache2.0/
 *
 * or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under the License. 
 *
 * ********************************************************************************************
 *
 *  Amazon Product Advertising API
 *  Signed Requests Sample Code
 *
 *  API Version: 2009-03-31
 *
 */

package org.loklak.api.amazon;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * This class contains all the logic for signing requests to the Amazon Product
 * Advertising API.
 */
public class SignedRequestsHelper {
	/**
	 * All strings are handled as UTF-8
	 */
	private static final String UTF8_CHARSET = "UTF-8";

	/**
	 * The HMAC algorithm required by Amazon
	 */
	private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";

	/**
	 * This is the URI for the service, don't change unless you really know what
	 * you're doing.
	 */
	private static final String REQUEST_URI = "/onca/xml";

	/**
	 * The sample uses HTTP GET to fetch the response. If you changed the sample
	 * to use HTTP POST instead, change the value below to POST.
	 */
	private static final String REQUEST_METHOD = "GET";

	private String endpoint = null;
	private String awsAccessKeyId = null;
	private String awsSecretKey = null;
	private String associatetag = null;
	private SecretKeySpec secretKeySpec = null;
	private Mac mac = null;

	/**
	 * You must provide the three values below to initialize the helper.
	 * 
	 * @param endpoint
	 *            Destination for the requests.
	 * @param awsAccessKeyId
	 *            Your AWS Access Key ID
	 * @param awsSecretKey
	 *            Your AWS Secret Key
	 */
	public static SignedRequestsHelper getInstance(String endpoint, String awsAccessKeyId, String awsSecretKey,
			String associatetag) throws IllegalArgumentException, UnsupportedEncodingException,
			NoSuchAlgorithmException, InvalidKeyException {
		if (null == endpoint || endpoint.length() == 0) {
			throw new IllegalArgumentException("endpoint is null or empty");
		}
		if (null == awsAccessKeyId || awsAccessKeyId.length() == 0) {
			throw new IllegalArgumentException("awsAccessKeyId is null or empty");
		}
		if (null == awsSecretKey || awsSecretKey.length() == 0) {
			throw new IllegalArgumentException("awsSecretKey is null or empty");
		}

		if (null == associatetag || associatetag.length() == 0) {
			throw new IllegalArgumentException("associatetag is null or empty");
		}

		SignedRequestsHelper instance = new SignedRequestsHelper();
		instance.endpoint = endpoint.toLowerCase();
		instance.awsAccessKeyId = awsAccessKeyId;
		instance.awsSecretKey = awsSecretKey;
		instance.associatetag = associatetag;

		byte[] secretyKeyBytes = instance.awsSecretKey.getBytes(UTF8_CHARSET);
		instance.secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
		instance.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
		instance.mac.init(instance.secretKeySpec);

		return instance;
	}

	/**
	 * The construct is private since we'd rather use getInstance()
	 */
	private SignedRequestsHelper() {
	}

	/**
	 * This method signs requests in hashmap form. It returns a URL that should
	 * be used to fetch the response. The URL returned should not be modified in
	 * any way, doing so will invalidate the signature and Amazon will reject
	 * the request.
	 */
	public String sign(Map params) {
		// Let's add the AWSAccessKeyId, AssociateTag and Timestamp parameters
		// to the request.
		params.put("AWSAccessKeyId", this.awsAccessKeyId);
		params.put("AssociateTag", this.associatetag);
		params.put("Timestamp", this.timestamp());

		// The parameters need to be processed in lexicographical order, so
		// we'll
		// use a TreeMap implementation for that.
		SortedMap sortedParamMap = new TreeMap(params);

		// get the canonical form the query string
		String canonicalQS = this.canonicalize(sortedParamMap);

		// create the string upon which the signature is calculated
		String toSign = REQUEST_METHOD + "\n" + this.endpoint + "\n" + REQUEST_URI + "\n" + canonicalQS;

		// get the signature
		String hmac = this.hmac(toSign);
		String sig = this.percentEncodeRfc3986(hmac);

		// construct the URL
		String url = "http://" + this.endpoint + REQUEST_URI + "?" + canonicalQS + "&Signature=" + sig;

		return url;
	}

	/**
	 * This method signs requests in query-string form. It returns a URL that
	 * should be used to fetch the response. The URL returned should not be
	 * modified in any way, doing so will invalidate the signature and Amazon
	 * will reject the request.
	 */
	public String sign(String queryString) {
		// let's break the query string into it's constituent name-value pairs
		Map params = this.createParameterMap(queryString);

		// then we can sign the request as before
		return this.sign(params);
	}

	/**
	 * Compute the HMAC.
	 * 
	 * @param stringToSign
	 *            String to compute the HMAC over.
	 * @return base64-encoded hmac value.
	 */
	private String hmac(String stringToSign) {
		String signature = null;
		byte[] data;
		byte[] rawHmac;
		try {
			data = stringToSign.getBytes(UTF8_CHARSET);
			rawHmac = mac.doFinal(data);
			signature = Base64.getEncoder().encodeToString(rawHmac);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
		}
		return signature;
	}

	/**
	 * Generate a ISO-8601 format timestamp as required by Amazon.
	 * 
	 * @return ISO-8601 format timestamp.
	 */
	private String timestamp() {
		String timestamp = null;
		Calendar cal = Calendar.getInstance();
		DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		dfm.setTimeZone(TimeZone.getTimeZone("GMT"));
		timestamp = dfm.format(cal.getTime());
		return timestamp;
	}

	/**
	 * Canonicalize the query string as required by Amazon.
	 * 
	 * @param sortedParamMap
	 *            Parameter name-value pairs in lexicographical order.
	 * @return Canonical form of query string.
	 */
	private String canonicalize(SortedMap sortedParamMap) {
		if (sortedParamMap.isEmpty()) {
			return "";
		}

		StringBuffer buffer = new StringBuffer();
		Iterator<Map.Entry> iter = sortedParamMap.entrySet().iterator();

		while (iter.hasNext()) {
			Map.Entry kvpair = iter.next();
			buffer.append(percentEncodeRfc3986(kvpair.getKey()));
			buffer.append("=");
			buffer.append(percentEncodeRfc3986(kvpair.getValue()));
			if (iter.hasNext()) {
				buffer.append("&");
			}
		}
		String cannoical = buffer.toString();
		return cannoical;
	}

	/**
	 * Percent-encode values according the RFC 3986. The built-in Java
	 * URLEncoder does not encode according to the RFC, so we make the extra
	 * replacements.
	 * 
	 * @param s
	 *            decoded string
	 * @return encoded string per RFC 3986
	 */
	private String percentEncodeRfc3986(String s) {
		String out;
		try {
			out = URLEncoder.encode(s, UTF8_CHARSET).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
		} catch (UnsupportedEncodingException e) {
			out = s;
		}
		return out;
	}

	/**
	 * Takes a query string, separates the constituent name-value pairs and
	 * stores them in a hashmap.
	 * 
	 * @param queryString
	 * @return
	 */
	private Map createParameterMap(String queryString) {
		Map map = new HashMap();
		String[] pairs = queryString.split("&");

		for (String pair : pairs) {
			if (pair.length() < 1) {
				continue;
			}

			String[] tokens = pair.split("=", 2);
			for (int j = 0; j < tokens.length; j++) {
				try {
					tokens[j] = URLDecoder.decode(tokens[j], UTF8_CHARSET);
				} catch (UnsupportedEncodingException e) {
				}
			}
			switch (tokens.length) {
			case 1: {
				if (pair.charAt(0) == '=') {
					map.put("", tokens[0]);
				} else {
					map.put(tokens[0], "");
				}
				break;
			}
			case 2: {
				map.put(tokens[0], tokens[1]);
				break;
			}
			default: {
				// nothing
				break;
			}
			}
		}
		return map;
	}
}

Now things become a whole lot easier. We can straightaway sign our requests using this class, make our request authenticated, and get the result.

Now we need to figure out what we should get from the API. My idea was to use the Large ResponseGroup by default, so that we get all the possible info (the Large ResponseGroup encapsulates all other ResponseGroups), and also, we should enable searching both by ASIN and Product Name so that the API is efficient enough and can give proper results, i.e I had to implement both the ItemLookup and ItemSearch APIs. Also, I added an option to choose your own ResponseGroup so that you can select what all quantity of data, and what all data you want, and get the result.

So here is the code of the AmazonAPIService, which enables Susi Monetisation.


/**
 *  AmazonProductService
 *  Copyright 05.08.2016 by Shiven Mian, @shivenmian
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *  
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program in the file lgpl21.txt
 *  If not, see .
 */

package org.loklak.api.amazon;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONObject;
import org.json.XML;
import org.loklak.data.DAO;
import org.loklak.server.APIException;
import org.loklak.server.APIHandler;
import org.loklak.server.AbstractAPIHandler;
import org.loklak.server.Authorization;
import org.loklak.server.BaseUserRole;
import org.loklak.server.Query;
import org.loklak.tools.storage.JSONObjectWithDefault;
import org.w3c.dom.Document;

public class AmazonProductService extends AbstractAPIHandler implements APIHandler {

	private static final long serialVersionUID = 2279773523424505716L;

	// set your key configuration in config.properties under the Amazon API
	// Settings field
	private static final String AWS_ACCESS_KEY_ID = DAO.getConfig("aws_access_key_id", "randomxyz");
	private static final String AWS_SECRET_KEY = DAO.getConfig("aws_secret_key", "randomxyz");
	private static final String ASSOCIATE_TAG = DAO.getConfig("aws_associate_tag", "randomxyz");

	// using the USA locale
	private static final String ENDPOINT = "webservices.amazon.com";

	@Override
	public String getAPIPath() {
		return "/cms/amazonservice.json";
	}

	@Override
	public BaseUserRole getMinimalBaseUserRole() {
		return BaseUserRole.ANONYMOUS;
	}

	@Override
	public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) {
		return null;
	}

	public static JSONObject fetchResults(String requestUrl, String operation) {
		JSONObject itemlookup = new JSONObject(true);
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(requestUrl);
			DOMSource domSource = new DOMSource(doc);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.transform(domSource, result);
			JSONObject xmlresult = new JSONObject(true);
			xmlresult = XML.toJSONObject(writer.toString());
			JSONObject items = xmlresult.getJSONObject(operation).getJSONObject("Items");
			if (items.getJSONObject("Request").has("Errors")) {
				itemlookup.put("status", "error");
				itemlookup.put("reason",
						items.getJSONObject("Request").getJSONObject("Errors").getJSONObject("Error").get("Message"));
				return itemlookup;
			}
			itemlookup.put("number_of_items",
					(operation.equals("ItemLookupResponse") ? "1" : (items.getJSONArray("Item").length())));
			itemlookup.put("list_of_items", items);
		} catch (Exception e) {
			itemlookup.put("status", "error");
			itemlookup.put("reason", e);
			return itemlookup;
		}
		return itemlookup;
	}

	@Override
	public JSONObject serviceImpl(Query call, HttpServletResponse response, Authorization rights,
			JSONObjectWithDefault permissions) throws APIException {
		String ITEM_ID = call.get("id", "");
		String PRODUCT_NAME = call.get("q", "");
		String responsegroup = (call.get("response_group", "") != "" ? call.get("response_group", "") : "Large");
		if (!("".equals(ITEM_ID)) && ITEM_ID.length() != 0) {
			return itemLookup(ITEM_ID, responsegroup);
		} else if (!("".equals(PRODUCT_NAME)) && PRODUCT_NAME.length() != 0) {
			return itemSearch(PRODUCT_NAME, responsegroup);
		} else {
			return new JSONObject().put("error", "no parameters given");
		}
	}

	public JSONObject itemSearch(String query, String responsegroup) {
		JSONObject result = new JSONObject(true);
		SignedRequestsHelper helper;
		if (query.length() == 0 || "".equals(query)) {
			result.put("error", "Please specify a query to search");
			return result;
		}
		try {
			helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, ASSOCIATE_TAG);
		} catch (Exception e) {
			result.put("error", e.toString());
			return result;
		}
		String requestUrl = null;
		String queryString = "Service=AWSECommerceService&ResponseGroup=" + responsegroup
				+ "&Operation=ItemSearch&Keywords=" + query + "&SearchIndex=All";
		requestUrl = helper.sign(queryString);
		result = fetchResults(requestUrl, "ItemSearchResponse");
		return result;
	}

	public JSONObject itemLookup(String asin, String responsegroup) {
		SignedRequestsHelper helper;
		JSONObject result = new JSONObject(true);
		if (asin.length() == 0 || "".equals(asin)) {
			result.put("error", "Please specify an Item ID");
			return result;
		}

		try {
			helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, ASSOCIATE_TAG);
		} catch (Exception e) {
			result.put("error", e.toString());
			return result;
		}
		String requestUrl = null;
		String queryString = "Service=AWSECommerceService&ResponseGroup=" + responsegroup
				+ "&Operation=ItemLookup&ItemId=" + asin;
		requestUrl = helper.sign(queryString);
		result = fetchResults(requestUrl, "ItemLookupResponse");
		return result;
	}

}

As you can see in this code, I have taken in the parameters (either of q or ASIN, and responsegroup), and depending on type of param, I have decided whether to use the ItemLookup or the ItemSearch API (only these two as of now are relevant for Susi in real). The ResponseGroup is defaulted to Large, so even if you avoid the responsegroup param, you still get all the data. What next? I just built the query, signed it using the SignedRequestsHelper (note: the associate tags and the keys are in the config file as mentioned in my last blog post), and I then parse the returned XML and display it as a JSON.

We are yet to get this into Susi (in the form of questions), but that will be up soon. Susi can simply be monetised by sending in the URL (which contains our associate tag) along with the result, so that a person can go to the URL and we can get hits on that, for which we get paid by the Affiliates Program. But now, we have seen how we intend the API to work. Since the Product Advertising API is huge, we can always make this API more efficient and expand it, which is a future plan too.

Feedback, as always, is welcome. 🙂

Monetisation of Susi using the Amazon Product API (Part 2)

Monetisation of Susi using the Amazon Product API (Part 1)

I’ve worked with the loklak team on Susi for the past month, and we’re in that stage where we are mostly expanding the dataset we have. Susi is still nascent, mind you, but it does show a lot of promise in terms of the idea and the progress we have made.

In the past some posts, I covered OSM Analysis, integrating that into Susi, as well as Bot integration, and I also spoke about the need for Susi to increase its reach (which was the purpose for the Bot integration). For this purpose and the general purpose of making Susi more able to answer different queries, I dug around a lot of APIs, and came across the Amazon Product Advertising API, which answered both the reach and the dataset question.

Through the Amazon API, we can get a wide (really wide) range of information for products in its database. Along with ItemSearch (search Item by Name), ItemLookup (search Item by Amazon ID, known as ASIN), there are a host of other APIs: SimilarityLookup, BrowseNodes, even Virtual Carts (wherein you can add items to a remote virtual cart and get prices etc). And here comes the best thing: since you use the API with your Affiliate / Associate Tag and secret keys, if someone goes into a URL which is marked by your affiliate tag, you get paid for it.

So clearly, we can expand our dataset, as well as get an income by using this API, making it suitable for solving both the reach and the dataset problem. I will explain the usage of this API, as well as its integration into Susi in today’s and two more blog posts. Today, let’s go through the structure, as well as the operations of this API.

The Amazon API is a SOAP based API, which means we get the information as an XML. To access the API, Amazon has an authentication requirement. It gives you a set of API keys (through AWS): an AWS secret key, and an AWS access ID. In addition, you also need to apply for an associate tag at the AWS Affiliates Program. The reason for that is the API gives out URLs marked with our associate tag, and as mentioned above, one earns income after enough number of hits on those URLs. More can be seen here.

Once we have those keys, we decide the Operation that we need to perform: ItemLookup, ItemSearch etc (full list of operations here). And once that is done, we decide the Response Group. The Response Group defines the way that operation returns data, i.e the format, what all data does it return. This makes it very convenient for users to get exactly what they want, which makes it even more ideal for Susi. More about Response Groups here.

So what do we do with all this data? How do we even get the response from the API? That’s the fun part. Let us take an example with the ItemSearch API. We will get the Amazon data, i.e a list of products similar to or matching “the hunger games” for example.

Since Amazon API is SOAP, we need to build up the API request URL. We first decide on a locale. The Amazon locale is to be decided based on your AWS settings. Since I set up my AWS account as a USA locale, I use the USA endpoint of Amazon, namely webservices.amazon.com.

Once this is done we supply the following GET parameters:

1. Service (for most operations we use Service as AWSECommerceService)
2. AWS Access ID
3. AWS Associate Tag
4. Operation (in this case ItemSearch)
5. Keywords (i.e query, in this case “harry potter and the cursed child”)
6. Search Index (this is ONLY used for ItemSearch, in this case we put Search Index as All. It is basically which category to search in, it’s a compulsory param)

7. Response Group (optional, it’s defaulted to Small)
8. Timestamp (time of request)
9. Signature (Amazon uses Hmac algorithm to sign requests, so we need to supply a signature)

My implementation of the Amazon API uses a REST wrapper which uses java.util commands to get the Signature and the Timestamp etc, the rest has to be supplied by us. As of now, let’s see how a sample API request for the USA locale looks like:

http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[AWS Access Key ID]&AssociateTag=[Associate ID]&Operation=ItemSearch&Keywords=the%20hunger%20games&SearchIndex=Books&Timestamp=[YYYY-MM-DDThh:mm:ssZ]&Signature=[Request Signature]

I have then used w3c’s DOM to connect to the API, get the XML, and parse it, but here’s how the sample XML looks like:


<TotalResults>2849</TotalResults>
<TotalPages>285</TotalPages>
<MoreSearchResultsUrl>http://www.amazon.com/gp/redirect.html?linkCode=xm2&SubscriptionId=[AWS Access Key ID]&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3Dthe%2Bhunger%2Bgames%26url%3Dsearch-alias%253Dstripbooks&tag=[Associate ID]&creative=386001&camp=2025</MoreSearchResultsUrl>
<Item>
    <ASIN>0545670314</ASIN>
    <DetailPageURL>http://www.amazon.com/The-Hunger-Games-Trilogy-Mockingjay/dp/0545670314%3FSubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0545670314</DetailPageURL>
    <ItemLinks>
        <ItemLink>
            <Description>Technical Details</Description>
            <URL>http://www.amazon.com/The-Hunger-Games-Trilogy-Mockingjay/dp/tech-data/0545670314%3FSubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>Add To Baby Registry</Description>
            <URL>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3D0545670314%26SubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>Add To Wedding Registry</Description>
            <URL>http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3D0545670314%26SubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>Add To Wishlist</Description>
            <URL>http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3D0545670314%26SubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>Tell A Friend</Description>
            <URL>http://www.amazon.com/gp/pdp/taf/0545670314%3FSubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>All Customer Reviews</Description>
            <URL>http://www.amazon.com/review/product/0545670314%3FSubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
        <ItemLink>
            <Description>All Offers</Description>
            <URL>http://www.amazon.com/gp/offer-listing/0545670314%3FSubscriptionId%3D[AWS Access Key ID]%26tag%3D[Associate ID]%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D0545670314</URL>
        </ItemLink>
    </ItemLinks>
    <ItemAttributes>
        <Author>Suzanne Collins</Author>
        <Manufacturer>Scholastic Press</Manufacturer>
        <ProductGroup>Book</ProductGroup>
        <Title>The Hunger Games Trilogy: The Hunger Games / Catching Fire / Mockingjay</Title>
    </ItemAttributes>
</Item>

One thing to notice is the URLs in the XML result. See how it has the Associate tag and the Access ID mentioned in it? This is how the monetisation happens: when the users buy their products with links having our associate tags on them.

This is obviously just scratching the surface, the API itself has a whole lot of operations. I have given a necessary brief on how the API really works. In my next two blog posts, I will speak on building the Amazon API Service for loklak, and then integrating it into Susi. Feedback is welcome. 🙂

Monetisation of Susi using the Amazon Product API (Part 1)

Releasing the loklak Python SDK 1.7

Python is one of the most popular languages in which many developers from the open source community and startups write their applications, What makes this happen is the ease of usage for the developers to leverage the library. We noticed the same here at loklak, the data on the loklak server and the new integration of Susi could be leveraged with one line of code each by the developers using the library instead of writing complex reusable components to integrate loklak into their application.

Loklak Susi Python

In the v1.7 release, there have been major changes that’ve been made to the library SDK which includes direct parsing and conversion logic from one format to another i.e. XML => JSON / JSON => XML etc.., Added to this, the ability for Susi and for developers to leverage susi’s capabilities has also been integrated into the recent release. As the library matured, the library now also supports Python3 and Python2 simultaneously. It’s now very simple for a developer to leverage Susi’s capabilities because of the library.

To install the library you can do pip install python-loklak-api, works with both pip3 and pip2. Once the library is installed, it’s very simple to make queries to loklak and to susi with just a few lines of code. Here’s an example of how this could be used and the modularity and robustness with which the library has been built.

>>> from loklak import Loklak
>>> from pprint import pprint
>>> l = Loklak() # Uses the domain loklak.org
>>> susi_result = l.susi('Hi I am Sudheesh')
>>> pprint(susi_result)
{'answer_date': '2016-08-20T04:56:17.371Z',
 'answer_time': 11,
 'answers': [{'actions': [{'expression': 'Hi sudheesh.', 'type': 'answer'}],
              'data': [{'0': 'i am sudheesh', '1': 'sudheesh'}],
              'metadata': {'count': 1, 'hits': 1, 'offset': 0}}],
 'client_id': 'aG9zdF8xODMuODMuMTIuNzY=',
 'count': 1,
 'query': 'Hi I am Sudheesh',
 'query_date': '2016-08-20T04:56:17.360Z',
 'session': {'identity': {'anonymous': True,
                          'name': '183.83.12.76',
                          'type': 'host'}}}

Similarly, fetching the information for a search or a user is also equally easy

>>> l.search('rio')
>>> l.user('sudheesh001')

This makes it useful for hundreds of developers and plugins in Python to potentially leverage this library into various frameworks like Django, Flask, Pyramid or even run it from the command line interface. Head over to our github repository to learn more and detailed documentation.

Releasing the loklak Python SDK 1.7