Improved documentation for Loklak repos

Its the final week of GSoC 2016. All the projects are nearing their completion stage. Since one of the plugins from FOSSASIA (https://wordpress.org/plugins/tweets-widget/) is already in WordPress directory, I took this opportunity to write some documentation for other plugins and the plugin maintenance repo.

The documentation now verbosely describes the complete Heroku deployment procedure directly from Github as well as using the Git-Heroku toolbelt (see this).

Selection_023

Docs for updating to a newer version of WordPress have also been added.

Selection_022

Screenshots and relevant documentation regarding Loklak API was added to several plugins.

 

Selection_025
readme.txt of https://github.com/fossasia/wp-recent-tweet

Some screenshots of the plugin (wp-recent-tweet) added in the readme

Selection_026

Improved documentation for Loklak repos

First Loklak plugin added to WordPress directory

Recently first Loklak plugin was accepted in WordPress directory. We are planning to add more and more plugins with loklak integration and it is an awesome start. The plugin Tweets Widget is a minimalist tweet feed which can render tweets from Loklak.org API or Twitter API v1.1 .

The widget uses Twitter Auth WordPress API (wp-twitter-api) by _timwhitlock_ and Loklak’s PHP API for tweet rendering purposes. Both the APIs are added as submodules.

Tweets Widget shows tweet feed on your wordpress website. You can add its shortcode or just add it as a Widget using wordpress’s drag and drop feature.

It is compatible with both Twitter as well as Loklak API. The settings page allows you to select one of the two modes for your current feed (as shown below).

screenshot-2

After you provide the default settings, you have to provide a tweet title, handle, number of tweets and some more custom feature

screenshot-3

See the screenshot of a sample feed below.

screenshot-1

It uses loklak search API (code sample shown below).

Selection_020

The main widget code can be seen here.

First Loklak plugin added to WordPress directory

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)

Testing localhost-only Loklak APIs

Loklak provides several APIs which are localhost-only! i.e. only localhost clients are granted access. For example:

This feature makes it difficult to integrate testing of such APIs with the main test-suite. Since we use Travis-CI for online testing, we would have to create an extra connection setup for online testing and offline (localhost) testing.

So in this dilemma, I had to come up with an approach which would allow the test-suite to recognise Travis-CI and take necessary actions to handle such conditions. After some reading, I came across PHP’s getenv() function which provides information of current environment variables.

So, in order to write tests for localhost-only APIs, I used getenv() as a check to differentiate between Travis and local tests.

Selection_013

Using this approach, tests for Settings and Accounts API were added. Code samples shown below!

Selection_014

This approach improves the tested code-coverage and integrates all unit tests into one file!

Testing localhost-only Loklak APIs

Setting up plugins for test!

I spent most of this summer working on wordpress plugins. So when we were up with a substantial amount, we wanted to test them online. I discussed in a previous blog-post regarding putting an online wordpress implementation through Heroku. Once I was done with internal testing, the plugins were supposed to be released for common testing. Now, since we did not want to risk our service, we couldn’t provide admin rights to new users. So in order to overcome this problem I had the following options at my disposal:

  1. Create a script which would automatically activate and configure all plugins and show a basic plugin interface to users who are not logged in; OR
  2. Create a user with lesser privileges than administrator, but enough to view and modify plugin settings.

The problem with the first approach was its static nature. A user would not be able to test your service if he is not leveraged with all options your program provides. So, in order to ensure rigorous testing, I used the second approach.

WordPress, by default, provides 5 user-types:

  1. Administrator
  2. Editor
  3. Author
  4. Contributor
  5. Subscriber

As none of these user profiles fit the required job specification, I had to create my own user-type. After some brainstorming and searching, I found a pretty useful WordPress plugin (User Role Editor) which creates custom user profiles based on actions already present in WP suite. Once I installed the plugin on our WP installation, I used following steps to create my own user-profile called Loklak Tester. 

  • Click on ‘Users’ menu and then click on ‘User Role Editor’.

Selection_010

  • Here I selected the privileges I wanted for my user. Some of them are shown in the figure.

Selection_009

  • Once I was done, I clicked on Add Role and provided the required user-type name.
  • Below screenshot shows the menu for our new user-profile ‘Loklak Tester’.

Selection_011

Creation of this new user-profile would allow users to login using its credentials. Activate/deactivate, modify, edit plugins and change their settings. This would later act as a demo testing user which could be used by our audience to test our plugins on variety of levels.

Setting up plugins for test!