Skip to content

Instantly share code, notes, and snippets.

@vectoroc
Created August 10, 2010 21:11
Show Gist options
  • Save vectoroc/518021 to your computer and use it in GitHub Desktop.
Save vectoroc/518021 to your computer and use it in GitHub Desktop.
(function() {
var db = openDatabase('friends', '0', 'Offline friends storage', 1024*1024, function (db) {
db.changeVersion('', '0', function (t) {
t.executeSql('CREATE TABLE friends (id UNIQUE, name, ava)');
t.executeSql('CREATE TABLE history (event, data, time DEFAULT (CURRENT_TIMESTAMP))');
});
});
function logDeleted(friend) {
db.transaction(function(t) {
t.executeSql('INSERT INTO history (event, data) VALUES (?,?)', ['deleted', friend.id]);
});
}
function logAdded(friend) {
db.transaction(function(t) {
t.executeSql('INSERT INTO history (event, data) VALUES (?,?)', ['added', friend.id]);
t.executeSql('INSERT INTO friends (id, name, ava) VALUES (?,?,?)', [friend.id, friend.name, friend.ava]);
});
}
var friends_stored = {};
function loadStoredFriends() {
db.readTransaction(function(t){
t.executeSql('SELECT * FROM friends', [], function (t, data) {
for (var i = 0; i < data.rows.length; i++) {
var row = data.rows.item(i);
friends_stored[row.id] = row;
}
loadRemoteFriends();
});
});
}
var friends_remote = {};
function loadRemoteFriends() {
Ajax.Get({url:'friends.php',onDone: function(ajaxObj,responseText){
var data = eval('('+ responseText +')'), friends = [];
for (var i = 0, friend; i<data.friends.length; i++) {
var friend = data.friends[i];
friends_remote[friend[0]] = {id: friend[0], name: friend[1], ava: friend[2]};
}
logChanges();
}});
}
function logChanges() {
for (var id in friends_stored) {
if (!friends_remote[id]) logDeleted(friends_stored[id]);
}
for (var id in friends_remote) {
if (!friends_stored[id]) logAdded(friends_remote[id]);
}
db.readTransaction(function(t) {
t.executeSql('SELECT f.*, h.* FROM history h INNER JOIN friends f ON h.data = f.id ORDER BY h.event DESC', [], function(t, data) {
var result = [];
for (var i = 0; i < data.rows.length; i++) {
var row = data.rows.item(i);
result.push('<div><img width=40 height=40 src="' + row.ava + '"/><span style="padding: 2em 1em">' + row.name + '-' + row.time + ' ' + row.event + '</span></div>');
}
var mb = new MessageBox({title: 'History'});
mb.addButton({label: 'Ok', onClick: function(){mb.hide();} });
mb.content('<div style="overflow-y: scroll; height: 400px">' + result.join('') + '</div>').show();
});
});
}
loadStoredFriends();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment