Listing 1. Facebook E-mail Import Script

// This script will import data from exported emails
// into the facebook_stats table
include("qt.core");
include("qt.gui");

var statsFile = new QFile("/home/piggz/kexi_fb/updates.mbox");
var stat_date;
var new_fans;
var new_posts;
var visits;
var total_fans;
var idx;

var conn = Kexi.getConnection();
var table = conn.tableSchema("facebook_stats");

if (statsFile.open(QIODevice.ReadOnly)) {
  var ts = new QTextStream(statsFile);
  var i = 0;
  while (!ts.atEnd()) {
    // Process the file line by line,
    // grabbing data and adding records
    var line = ts.readLine();

    // Check date email sent
    idx = line.indexOf("Date:");
    if (idx == 0) {
      stat_date = Date.parse(line.slice(6, 40));
    }

    // Check for fans
    idx = line.indexOf("ans this week");
    if ( idx >= 0) {
      new_fans = line.slice(0, idx-2);
      total_fans = line.slice(line.indexOf("(") + 1,
                              line.indexOf("total") - 1);
    }

    // Check for wall posts
    idx = line.indexOf("all posts");
    if (idx >= 0) {
      new_posts = line.slice(0, idx-2) + 0;
    }

    // Check for visits
    idx = line.indexOf("isits to your");
    if (idx >= 0) {
      visits = line.slice(0,idx-2);

      // Should have all the data now so insert a record

      stat_date = new Date(stat_date);
      var short_date = stat_date.getFullYear() + "-"
                     + pad(stat_date.getMonth() + 1, 2) + "-"
                     + pad(stat_date.getDate(), 2);

      if (!conn.insertRecord(table, [++i,
                                     short_date,
                                     new_fans,
                                     new_posts,
                                     visits,
                                     total_fans])) {
            var msg = "Cannot insert into " + table.caption() + '\n';
            msg += "Date: " + stat_date.toDateString()
                 + " " + short_date + '\n';
            msg += "New Fans: " + new_fans + '\n';
            msg += "Total Fans: " + total_fans + '\n';
            msg += "New Posts: " + new_posts + '\n';
            msg += "Visits: " + visits;

            QMessageBox.information(0,"Error", msg);
      }
    }
  }
  QMessageBox.information(0, "Records Added:", i);
}

statsFile.close();

function pad(number, length) {
  var str = '' + number;
  while (str.length < length) {
    str = '0' + str;
  }
  return str;
}

