/www/src/ConversationStore.js
enyo.kind({
name: "ConversationStore",
kind: "Component",
conversations: {},
retentionWindow: 86400,
loadConversations: function() {
var len = localStorage.length;
for (var i = 0; i < len; i++) {
var key = localStorage.key(i);
if (key.match(/^conversation:/)) {
var jid = key.replace(/^conversation:/, '');
this.conversations[jid] = JSON.parse(localStorage[key]);
}
}
},
saveConversation: function(jid) {
if (!(jid in this.conversations)) return;
localStorage['conversation:' + jid] = JSON.stringify(this.conversations[jid]);
},
getConversation: function(jid) {
if (jid in this.conversations) {
// Be sure to return a copy
return this.conversations[jid].messages.slice(0);
} else {
return [];
}
},
getConversationSummary: function() {
var res = []
for (jid in this.conversations) {
var len = this.conversations[jid].messages.length;
var lastMessage = len > 0 ? this.conversations[jid].messages[len - 1] : '';
res.push({
jid: jid,
outbound: lastMessage.outbound,
message: lastMessage.message,
receivedTimestamp: lastMessage.receivedTimestamp
});
}
return res.sort(function(a, b) {
if (a.receivedTimestamp > b.receivedTimestamp)
return -1;
if (a.receivedTimestamp < b.receivedTimestamp)
return 1;
return 0;
});
},
appendConversation: function(jid, data) {
if (!(jid in this.conversations)) {
this.conversations[jid] = {
lastMessageTimestamp: 0,
messages: []
};
}
this.conversations[jid].messages.push(data);
this.conversations[jid].lastMessageTimestamp = (new Date()).getTime();
this.cullConversation(jid);
this.saveConversation(jid);
},
cullConversation: function(jid) {
// TODO: implement message culling by retentionWindow
}
});