The final part of Beats Per Mile worth mentioning is the Twitter integration.
The application was designed to send automated tweets on Gemma’s behalf from her personal Twitter account giving updates of her progress to those following.
Mainly the tweets would report her current location for the purposes of spectators waiting ahead, others would be sent at intervals of a mile or so to report pace and ongoing form.
Similar to the mechanism for fetching Instagram images at predetermined locations on the course, the application contained a list of agreed points at which to tweet.
These were at landmarks and certain spectator spots too, but also at course milestones — the first mile complete, halfway complete, one mile to go etc, as well as the start and finish.
The application monitored the elapsed distance and updated accordingly, grabbing the latest time and statistics from the RunKeeper data, as well as geolocating the tweet with the latest set of GPS coordinates.
Since Twitter deprecated support of Basic Auth, applications much authenticate users with OAuth to gain write access.
This means rather than handing over your username and password to applications and trust (hope) that they’re friendly — as used to be the only way — OAuth allows applications to request access on your behalf without users ever parting with precious login credentials. You simple give, or deny, permission.
Twitter offer a number of links to OAuth libraries for various languages to make the this job a lot easier. There are many Twitter specific OAuth libraries in particular, purposely tailored for the API.
I picked up PHP-based TwitterOAuth by Abraham Williams, which gets you up and running very rapidly.
The OAuth flow is documented at length, but essentially performs three major tasks:
- Obtains access from Twitter to make requests on behalf of a user
- Directs a user to Twitter in order to authenticate their account
- Gains authorisation from the user to make requests on their behalf
This is achieved with a cycle of exchanging authenticating tokens between application and Twitter to verify permission. TwitterOAuth particularly creates a session object in your application and rebuilds itself with each token exchange to remain contained in a single class instance.
In a very abridged manner, something like the following:
// Build TwitterOAuth object with client credentials
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
// Get temporary credentials to allow application to make requests and set callback
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
This initial call verifies your application has access the Twitter API, basically that it’s registered and good to go. Twitter returns two tokens, if successful, that we store:
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
Then the application sends the user to Twitter to authorise it’s access, using a URL generated with the token received above:
$authoriseURL = $connection->getAuthorizeURL($request_token['oauth_token']);
header(‘Location: ‘ . $authoriseURL);
On successful authorisation Twitter will return the user to your callback URL (set above) with a verification token. TwitterOAuth now rebuilds for the first time with the OAuth tokens in our session and uses the new verification token to get an a new access token which will grant us user account access:
// Create TwitterOAuth object with application tokens
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Request access tokens from Twitter on behalf of current user with verifier
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
This final request gets us two OAuth tokens specific to the current user, allowing us to make requests on their behalf, with which TwitterOAuth rebuilds again:
// Rebuild TwitterOAuth object with user granted tokens
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
// Test that everything is working
The dance made a hell of a lot easier with a library such as this.
Usually applications store these tokens final two tokens, the user generated oauth_token and oauth_token_secret, which saves the need to authorise the user again.
Storing these details (in a session or database) means that a username and password need not be saved. The tokens are good until the user revokes access, no sensitive information is ever released to the application, all the user ever gives is their permission.
With access tokens stored, the connection to Twitter is a lot simpler — just create the TwitterOAuth object with those user-generated codes as in the very last step, without any of the redirecting to and from Twitter.com. Of course, those tokens could only have ever been obtained by carrying out the full process to begin with.
Beats Per Mile is a single-user case application, so Gemma only had to authenticate the application once and then we hard-coded them into the scripts.
With access granted the application was free to send out updates, based on the run data we were collecting and posting it directly.
As mentioned, locations translated into distances and that’s when we tweeted.
At mile twenty, it looked back at the mile splits so far and reported which were the fastest:
Relying on the total reported distance alone was flawed. There was a slight hiccup when RunKeeper lost GPS coverage under Blackfriars tunnel and in an attempt to compensate found the nearest location to be the other side of the Thames.
This caused a problem by adding extra distance to her total, so some of the latter tweets (“one mile to go”, for example) posted a little prematurely.
It was more of a problem for Gemma when running, the app announcing in her ear that she’d run further than she had, disheartened to see mile markers on the course thought to have already passed.
This is also why the total distance on the site clocks up to 27.65 miles, the race was long enough as it is!
The final touch to was to drop them on the map, alongside the Instagram images.