signal-desktop/js/models/threads.js

122 lines
3.3 KiB
JavaScript
Raw Normal View History

// vim: ts=2:sw=2:expandtab:
var Whisper = Whisper || {};
(function () {
'use strict';
var Thread = Backbone.Model.extend({
defaults: function() {
return {
name: 'New Group',
image: '/images/default.png',
unreadCount: 0,
timestamp: new Date().getTime(),
active: true
};
},
validate: function(attributes, options) {
var required = ['type', 'timestamp', 'image', 'name'];
var missing = _.filter(required, function(attr) { return !attributes[attr]; });
if (missing.length) { return "Thread must have " + missing; }
},
sendMessage: function(message) {
var timestamp = Date.now();
this.messages().add({ type: 'outgoing',
body: message,
threadId: this.id,
timestamp: timestamp }).save();
this.save({ timestamp: timestamp,
unreadCount: 0,
active: true});
2014-06-08 01:05:11 +00:00
if (this.get('type') == 'private') {
var promise = textsecure.messaging.sendMessageToNumber(this.get('id'), message, []);
2014-06-08 01:05:11 +00:00
}
else {
var promise = textsecure.messaging.sendMessageToGroup(this.get('groupId'), message, []);
2014-06-08 01:05:11 +00:00
}
promise.then(
function(result) {
console.log(result);
}
).catch(
function(error) {
console.log(error);
}
);
},
messages: function() {
if (!this.messageCollection) {
this.messageCollection = new Whisper.MessageCollection([], {threadId: this.id});
}
return this.messageCollection;
},
});
Whisper.Threads = new (Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("Threads"),
model: Thread,
comparator: function(m) {
return -m.get('timestamp');
},
findOrCreate: function(attributes) {
var thread = Whisper.Threads.add(attributes, {merge: true});
thread.save();
return thread;
},
createGroup: function(recipients, name) {
var attributes = {};
attributes = {
name : name,
numbers : recipients,
type : 'group',
};
var thread = this.findOrCreate(attributes);
return textsecure.messaging.createGroup(recipients, name).then(function(groupId) {
2014-10-17 21:32:37 +00:00
thread.set('id', getString(groupId));
2014-10-17 20:11:08 +00:00
thread.set('groupId', getString(groupId));
thread.save();
return thread;
});
},
findOrCreateForRecipient: function(recipient) {
var attributes = {};
2014-06-08 01:05:11 +00:00
attributes = {
id : recipient,
name : recipient,
type : 'private',
};
return this.findOrCreate(attributes);
},
findOrCreateForIncomingMessage: function(decrypted) {
var attributes = {};
if (decrypted.message.group) {
attributes = {
2014-10-17 21:32:37 +00:00
id : decrypted.message.group.id,
2014-10-17 00:50:36 +00:00
groupId : decrypted.message.group.id,
name : decrypted.message.group.name || 'New group',
type : 'group',
};
} else {
attributes = {
id : decrypted.pushMessage.source,
name : decrypted.pushMessage.source,
type : 'private'
};
}
return this.findOrCreate(attributes);
}
}))();
})();