Code Break

How we track the keyboard stats on the new res.im

Written by @mikealmond • Designed by @andrewprocter

When launching a new site for ourselves we typically like to include a couple of unique, interesting features that we may not have the opportunity to work on otherwise.

The latest iteration (launched just before the holidays) features a stats section that has generated a few questions; particularly around how the daily keyboard stats component works.

It was important to us to ensure the stats we publish on the new site are live and as accurate as possible on page load. There are some occasions where we increment the value to simulate keystrokes.

So, here's how it works:

Each workstation in our office has a program called "Typingstats" installed. You can purchase a copy from the App Store for $0.99.

Typingstats uses an SQLite DB to store daily keystroke totals. Unfortunately, the app only flushes data to this file every hour. In order to force an update on the SQLite file and publish more up-to-date stats to our site we have to restart the app.

Restart is achieved with the following shell script:

#!/bin/sh
osascript -e 'tell application "Typingstats" to quit'
open /Applications/Typingstats.app/

php -q ~/transmitKeyStrokes.php

The last line of the shell script calls a PHP script that parses the SQLite database and pushes the data to a MySQL database stored on our hosting server. It looks something like this:

#!/usr/bin/env php -q
<?php
  $db = new PDO("sqlite:~/Library/Application Support/Typingstats/keypresses.db");
  $result = $db->query('SELECT * FROM keyPresses ORDER BY date, amount DESC');

  // insert the result into the database

Next, we wrote some methods to pull stats based on user, key code and date. We have a few todo's that we'd like to complete and implement. The major one being the integration of our PHP WebSockets library; Ratchet -- this would allow for more accurate increments while a visitor is on our site.

And that's how it works, now you know. Now back to typing…