1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-28 05:03:59 +03:00

Fix up stylistic warnings.

This commit is contained in:
Kegan Dougal
2015-06-03 10:37:41 +01:00
parent 67931f05ce
commit bdaad5b940
2 changed files with 112 additions and 76 deletions

View File

@@ -34,5 +34,9 @@ matrixcs.request(function(opts, callback) {
}); });
return defer.promise; return defer.promise;
}); });
/**
* Export a modified matrix library with Promise support.
*/
module.exports = matrixcs; module.exports = matrixcs;

View File

@@ -9,7 +9,7 @@ TODO:
*/ */
// wrap in a closure for browsers // wrap in a closure for browsers
var init = function(exports){ var init = function(exports) {
// expose the underlying request object so different environments can use // expose the underlying request object so different environments can use
// different request libs (e.g. request or browser-request) // different request libs (e.g. request or browser-request)
var request; var request;
@@ -35,7 +35,7 @@ var init = function(exports){
var requiredKeys = [ var requiredKeys = [
"baseUrl" "baseUrl"
]; ];
for (var i=0; i<requiredKeys.length; i++) { for (var i = 0; i < requiredKeys.length; i++) {
if (!credentials.hasOwnProperty(requiredKeys[i])) { if (!credentials.hasOwnProperty(requiredKeys[i])) {
throw new Error("Missing required key: " + requiredKeys[i]); throw new Error("Missing required key: " + requiredKeys[i]);
} }
@@ -61,11 +61,11 @@ var init = function(exports){
var HEADERS = { var HEADERS = {
"User-Agent": "matrix-js" "User-Agent": "matrix-js"
}; };
// Basic DAOs to abstract slightly from the line protocol and let the // Basic DAOs to abstract slightly from the line protocol and let the
// application customise events with domain-specific info // application customise events with domain-specific info
// (e.g. chat-specific semantics) if it so desires. // (e.g. chat-specific semantics) if it so desires.
/* /*
* Construct a Matrix Event object * Construct a Matrix Event object
* @param {Object} event The raw event to be wrapped in this DAO * @param {Object} event The raw event to be wrapped in this DAO
@@ -74,7 +74,7 @@ var init = function(exports){
this.event = event || {}; this.event = event || {};
} }
exports.MatrixEvent = MatrixEvent; exports.MatrixEvent = MatrixEvent;
MatrixEvent.prototype = { MatrixEvent.prototype = {
getId: function() { getId: function() {
return this.event.event_id; return this.event.event_id;
@@ -98,23 +98,23 @@ var init = function(exports){
return this.event.state_key !== undefined; return this.event.state_key !== undefined;
}, },
}; };
function MatrixInMemoryStore() { function MatrixInMemoryStore() {
this.rooms = { this.rooms = {
// state: { }, // state: { },
// timeline: [ ], // timeline: [ ],
}; };
this.presence = { this.presence = {
// presence objects keyed by userId // presence objects keyed by userId
}; };
} }
exports.MatrixInMemoryStore = MatrixInMemoryStore; exports.MatrixInMemoryStore = MatrixInMemoryStore;
// XXX: this is currently quite procedural - we could possibly pass back // XXX: this is currently quite procedural - we could possibly pass back
// models of Rooms, Users, Events, etc instead. // models of Rooms, Users, Events, etc instead.
MatrixInMemoryStore.prototype = { MatrixInMemoryStore.prototype = {
/* /*
* Add an array of one or more state MatrixEvents into the store, overwriting * Add an array of one or more state MatrixEvents into the store, overwriting
* any existing state with the same {room, type, stateKey} tuple. * any existing state with the same {room, type, stateKey} tuple.
@@ -144,14 +144,15 @@ var init = function(exports){
setStateEvent: function(stateEvent) { setStateEvent: function(stateEvent) {
this.setStateEvents([stateEvent]); this.setStateEvents([stateEvent]);
}, },
/* /*
* Return a list of MatrixEvents from the store * Return a list of MatrixEvents from the store
* @param {String} roomId the Room ID whose state is to be returned * @param {String} roomId the Room ID whose state is to be returned
* @param {String} type the type of the state events to be returned (optional) * @param {String} type the type of the state events to be returned (optional)
* @param {String} stateKey the stateKey of the state events to be returned * @param {String} stateKey the stateKey of the state events to be returned
* (optional, requires type to be specified) * (optional, requires type to be specified)
* @return {MatrixEvent[]} an array of MatrixEvents from the store, filtered by roomid, type and state key. * @return {MatrixEvent[]} an array of MatrixEvents from the store,
* filtered by roomid, type and state key.
*/ */
getStateEvents: function(roomId, type, stateKey) { getStateEvents: function(roomId, type, stateKey) {
var stateEvents = []; var stateEvents = [];
@@ -160,11 +161,13 @@ var init = function(exports){
if (this.rooms[roomId].state.hasOwnProperty(type)) { if (this.rooms[roomId].state.hasOwnProperty(type)) {
for (stateKey in this.rooms[roomId].state[type]) { for (stateKey in this.rooms[roomId].state[type]) {
if (this.rooms[roomId].state[type].hasOwnProperty(stateKey)) { if (this.rooms[roomId].state[type].hasOwnProperty(stateKey)) {
stateEvents.push(this.rooms[roomId].state[type][stateKey]); stateEvents.push(
this.rooms[roomId].state[type][stateKey]
);
} }
} }
} }
} }
return stateEvents; return stateEvents;
} }
else if (stateKey === undefined) { else if (stateKey === undefined) {
@@ -179,19 +182,20 @@ var init = function(exports){
return [this.rooms[roomId].state[type][stateKey]]; return [this.rooms[roomId].state[type][stateKey]];
} }
}, },
/* /*
* Return a single state MatrixEvent from the store for the given roomId * Return a single state MatrixEvent from the store for the given roomId
* and type. * and type.
* @param {String} roomId the Room ID whose state is to be returned * @param {String} roomId the Room ID whose state is to be returned
* @param {String} type the type of the state events to be returned * @param {String} type the type of the state events to be returned
* @param {String} stateKey the stateKey of the state events to be returned * @param {String} stateKey the stateKey of the state events to be returned
* @return {MatrixEvent} a single MatrixEvent from the store, filtered by roomid, type and state key. * @return {MatrixEvent} a single MatrixEvent from the store, filtered
* by roomid, type and state key.
*/ */
getStateEvent: function(roomId, type, stateKey) { getStateEvent: function(roomId, type, stateKey) {
return this.rooms[roomId].state[type][stateKey]; return this.rooms[roomId].state[type][stateKey];
}, },
/* /*
* Adds a list of arbitrary MatrixEvents into the store. * Adds a list of arbitrary MatrixEvents into the store.
* If the event is a state event, it is also updates state. * If the event is a state event, it is also updates state.
@@ -206,7 +210,7 @@ var init = function(exports){
var roomId = event.room_id; var roomId = event.room_id;
if (this.rooms[roomId] === undefined) { if (this.rooms[roomId] === undefined) {
this.rooms[roomId] = {}; this.rooms[roomId] = {};
} }
if (this.rooms[roomId].timeline === undefined) { if (this.rooms[roomId].timeline === undefined) {
this.rooms[roomId].timeline = []; this.rooms[roomId].timeline = [];
} }
@@ -216,7 +220,7 @@ var init = function(exports){
this.rooms[roomId].timeline.push(events[i]); this.rooms[roomId].timeline.push(events[i]);
} }
}, },
/* /*
* Get the timeline of events for a given room * Get the timeline of events for a given room
* TODO: ordering! * TODO: ordering!
@@ -224,18 +228,18 @@ var init = function(exports){
getEvents: function(roomId) { getEvents: function(roomId) {
return this.room[roomId].timeline; return this.room[roomId].timeline;
}, },
setPresenceEvents: function(presenceEvents) { setPresenceEvents: function(presenceEvents) {
for (var i = 0; i < presenceEvents.length; i++) { for (var i = 0; i < presenceEvents.length; i++) {
var matrixEvent = presenceEvents[i]; var matrixEvent = presenceEvents[i];
this.presence[matrixEvent.event.user_id] = matrixEvent; this.presence[matrixEvent.event.user_id] = matrixEvent;
} }
}, },
getPresenceEvents: function(userId) { getPresenceEvents: function(userId) {
return this.presence[userId]; return this.presence[userId];
}, },
getRoomList: function() { getRoomList: function() {
var roomIds = []; var roomIds = [];
for (var roomId in this.rooms) { for (var roomId in this.rooms) {
@@ -245,10 +249,10 @@ var init = function(exports){
} }
return roomIds; return roomIds;
}, },
// TODO // TODO
//setMaxHistoryPerRoom: function(maxHistory) {}, //setMaxHistoryPerRoom: function(maxHistory) {},
// TODO // TODO
//reapOldMessages: function() {}, //reapOldMessages: function() {},
}; };
@@ -258,22 +262,24 @@ var init = function(exports){
return this.credentials.accessToken !== undefined && return this.credentials.accessToken !== undefined &&
this.credentials.userId !== undefined; this.credentials.userId !== undefined;
}, },
// Higher level APIs // Higher level APIs
// ================= // =================
// TODO: stuff to handle: // TODO: stuff to handle:
// local echo // local echo
// event dup suppression? - apparently we should still be doing this // event dup suppression? - apparently we should still be doing this
// tracking current display name / avatar per-message // tracking current display name / avatar per-message
// pagination // pagination
// re-sending (including persisting pending messages to be sent) // re-sending (including persisting pending messages to be sent)
// - Need a nice way to callback the app for arbitrary events like displayname changes // - Need a nice way to callback the app for arbitrary events like
// displayname changes
// due to ambiguity (or should this be on a chat-specific layer)? // due to ambiguity (or should this be on a chat-specific layer)?
// reconnect after connectivity outages // reconnect after connectivity outages
/* /*
* Helper method for retrieving the name of a room suitable for display in the UI * Helper method for retrieving the name of a room suitable for display
* in the UI
* TODO: in future, this should be being generated serverside. * TODO: in future, this should be being generated serverside.
* @param {String} roomId ID of room whose name is to be resolved * @param {String} roomId ID of room whose name is to be resolved
* @return {String} human-readable label for room. * @return {String} human-readable label for room.
@@ -283,17 +289,18 @@ var init = function(exports){
if (!this.store) { if (!this.store) {
return roomId; return roomId;
} }
// check for an alias, if any. for now, assume first alias is the official one. // check for an alias, if any. for now, assume first alias is the
// official one.
var alias; var alias;
var mRoomAliases = this.store.getStateEvents(roomId, 'm.room.aliases')[0]; var mRoomAliases = this.store.getStateEvents(roomId, 'm.room.aliases')[0];
if (mRoomAliases) { if (mRoomAliases) {
alias = mRoomAliases.event.content.aliases[0]; alias = mRoomAliases.event.content.aliases[0];
} }
var mRoomName = this.store.getStateEvent(roomId, 'm.room.name', ''); var mRoomName = this.store.getStateEvent(roomId, 'm.room.name', '');
if (mRoomName) { if (mRoomName) {
return mRoomName.event.content.name + (alias ? " (" + alias + ")": ""); return mRoomName.event.content.name + (alias ? " (" + alias + ")" : "");
} }
else if (alias) { else if (alias) {
return alias; return alias;
@@ -304,37 +311,52 @@ var init = function(exports){
.filter(function(event) { .filter(function(event) {
return event.event.user_id !== userId; return event.event.user_id !== userId;
}); });
if (members.length === 0) { if (members.length === 0) {
return "Unknown"; return "Unknown";
} }
else if (members.length == 1) { else if (members.length == 1) {
return members[0].event.content.displayname || members[0].event.user_id; return (
members[0].event.content.displayname ||
members[0].event.user_id
);
} }
else if (members.length == 2) { else if (members.length == 2) {
return (members[0].event.content.displayname || members[0].event.user_id) + " and " + return (
(members[1].event.content.displayname || members[1].event.user_id); (members[0].event.content.displayname ||
members[0].event.user_id) +
" and " +
(members[1].event.content.displayname ||
members[1].event.user_id)
);
} }
else { else {
return (members[0].event.content.displayname || members[0].event.user_id) + " and " + return (
(members.length - 1) + " others"; (members[0].event.content.displayname ||
members[0].event.user_id) +
" and " +
(members.length - 1) + " others"
);
} }
} }
}, },
/* /*
* Helper method for retrieving the name of a user suitable for display in the UI * Helper method for retrieving the name of a user suitable for display
* in the context of a room - i.e. disambiguating from any other users in the room. * in the UI in the context of a room - i.e. disambiguating from any
* XXX: This could perhaps also be generated serverside, perhaps by just passing * other users in the room.
* a 'disambiguate' flag down on membership entries which have ambiguous displaynames? * XXX: This could perhaps also be generated serverside, perhaps by just passing
* a 'disambiguate' flag down on membership entries which have ambiguous
* displaynames?
* @param {String} userId ID of the user whose name is to be resolved * @param {String} userId ID of the user whose name is to be resolved
* @param {String} roomId ID of room to be used as the context for resolving the name * @param {String} roomId ID of room to be used as the context for
* resolving the name.
* @return {String} human-readable name of the user. * @return {String} human-readable name of the user.
*/ */
getFriendlyDisplayName: function(userId, roomId) { getFriendlyDisplayName: function(userId, roomId) {
// we need a store to track the inputs for calculating display names // we need a store to track the inputs for calculating display names
if (!this.store) { return userId; } if (!this.store) { return userId; }
var displayName; var displayName;
var memberEvent = this.store.getStateEvent(roomId, 'm.room.member', userId); var memberEvent = this.store.getStateEvent(roomId, 'm.room.member', userId);
if (memberEvent && memberEvent.event.content.displayname) { if (memberEvent && memberEvent.event.content.displayname) {
@@ -343,12 +365,12 @@ var init = function(exports){
else { else {
return userId; return userId;
} }
var members = this.store.getStateEvents(roomId, 'm.room.member') var members = this.store.getStateEvents(roomId, 'm.room.member')
.filter(function(event) { .filter(function(event) {
return event.event.content.displayname === displayName; return event.event.content.displayname === displayName;
}); });
if (members.length > 1) { if (members.length > 1) {
return displayName + " (" + userId + ")"; return displayName + " (" + userId + ")";
} }
@@ -361,17 +383,21 @@ var init = function(exports){
* High level helper method to call initialSync, emit the resulting events, * High level helper method to call initialSync, emit the resulting events,
* and then start polling the eventStream for new events. * and then start polling the eventStream for new events.
* @param {function} callback Callback invoked whenever new event are available * @param {function} callback Callback invoked whenever new event are available
* @param {Number} historyLen amount of historical timeline events to emit during from the initial sync * @param {Number} historyLen amount of historical timeline events to
* emit during from the initial sync.
*/ */
startClient: function(callback, historyLen) { startClient: function(callback, historyLen) {
historyLen = historyLen || 12; historyLen = historyLen || 12;
var self = this; var self = this;
if (!this.fromToken) { if (!this.fromToken) {
this.initialSync(historyLen, function(err, data) { this.initialSync(historyLen, function(err, data) {
if (err) { if (err) {
if (this.config && this.config.debug) { if (this.config && this.config.debug) {
console.error("startClient error on initialSync: %s", JSON.stringify(err)); console.error(
"startClient error on initialSync: %s",
JSON.stringify(err)
);
} }
callback(err); callback(err);
} else { } else {
@@ -385,7 +411,9 @@ var init = function(exports){
events.push(new MatrixEvent(data.rooms[i].state[j])); events.push(new MatrixEvent(data.rooms[i].state[j]));
} }
for (j = 0; j < data.rooms[i].messages.chunk.length; j++) { for (j = 0; j < data.rooms[i].messages.chunk.length; j++) {
events.push(new MatrixEvent(data.rooms[i].messages.chunk[j])); events.push(
new MatrixEvent(data.rooms[i].messages.chunk[j])
);
} }
} }
callback(undefined, events, false); callback(undefined, events, false);
@@ -398,7 +426,7 @@ var init = function(exports){
this._pollForEvents(callback); this._pollForEvents(callback);
} }
}, },
_pollForEvents: function(callback) { _pollForEvents: function(callback) {
var self = this; var self = this;
if (!this.clientRunning) { if (!this.clientRunning) {
@@ -407,7 +435,10 @@ var init = function(exports){
this.eventStream(this.fromToken, 30000, function(err, data) { this.eventStream(this.fromToken, 30000, function(err, data) {
if (err) { if (err) {
if (this.config && this.config.debug) { if (this.config && this.config.debug) {
console.error("error polling for events via eventStream: %s", JSON.stringify(err)); console.error(
"error polling for events via eventStream: %s",
JSON.stringify(err)
);
} }
callback(err); callback(err);
// retry every few seconds // retry every few seconds
@@ -419,15 +450,16 @@ var init = function(exports){
var events = []; var events = [];
for (var j = 0; j < data.chunk.length; j++) { for (var j = 0; j < data.chunk.length; j++) {
events.push(new MatrixEvent(data.chunk[j])); events.push(new MatrixEvent(data.chunk[j]));
} }
callback(undefined, events, true); callback(undefined, events, true);
self._pollForEvents(callback); self._pollForEvents(callback);
} }
}); });
}, },
/* /*
* High level helper method to stop the client from polling and allow a clean shutdown * High level helper method to stop the client from polling and allow a
* clean shutdown.
*/ */
stopClient: function() { stopClient: function() {
this.clientRunning = false; this.clientRunning = false;
@@ -449,12 +481,12 @@ var init = function(exports){
}, },
setRoomName: function(roomId, name, callback) { setRoomName: function(roomId, name, callback) {
return this.sendStateEvent(roomId, "m.room.name", {name: name}, return this.sendStateEvent(roomId, "m.room.name", {name: name},
undefined, callback); undefined, callback);
}, },
setRoomTopic: function(roomId, topic, callback) { setRoomTopic: function(roomId, topic, callback) {
return this.sendStateEvent(roomId, "m.room.topic", {topic: topic}, return this.sendStateEvent(roomId, "m.room.topic", {topic: topic},
undefined, callback); undefined, callback);
}, },
@@ -592,7 +624,7 @@ var init = function(exports){
}, },
invite: function(roomId, userId, callback) { invite: function(roomId, userId, callback) {
return this._membershipChange(roomId, userId, "invite", undefined, return this._membershipChange(roomId, userId, "invite", undefined,
callback); callback);
}, },
@@ -629,7 +661,7 @@ var init = function(exports){
); );
return this._doAuthedRequest(callback, "PUT", path, undefined, { return this._doAuthedRequest(callback, "PUT", path, undefined, {
membership : membershipValue, membership: membershipValue,
reason: reason reason: reason
}); });
}, },
@@ -656,11 +688,11 @@ var init = function(exports){
getProfileInfo: function(userId, info, callback) { getProfileInfo: function(userId, info, callback) {
if (isFunction(info)) { callback = info; info = undefined; } if (isFunction(info)) { callback = info; info = undefined; }
var path = info ? var path = info ?
encodeUri("/profile/$userId/$info", encodeUri("/profile/$userId/$info",
{ $userId: userId, $info: info } ) : { $userId: userId, $info: info }) :
encodeUri("/profile/$userId", encodeUri("/profile/$userId",
{ $userId: userId } ); { $userId: userId });
return this._doAuthedRequest(callback, "GET", path); return this._doAuthedRequest(callback, "GET", path);
}, },
@@ -710,7 +742,7 @@ var init = function(exports){
}); });
var validStates = ["offline", "online", "unavailable"]; var validStates = ["offline", "online", "unavailable"];
if (validStates.indexOf(presence) == -1) { if (validStates.indexOf(presence) == -1) {
throw new Error("Bad presence value: "+presence); throw new Error("Bad presence value: " + presence);
} }
var content = { var content = {
presence: presence presence: presence
@@ -758,7 +790,7 @@ var init = function(exports){
self.store.setPresenceEvents( self.store.setPresenceEvents(
map(data.presence, eventMapper) map(data.presence, eventMapper)
); );
for (var i = 0 ; i < data.rooms.length; i++) { for (var i = 0; i < data.rooms.length; i++) {
self.store.setStateEvents( self.store.setStateEvents(
map(data.rooms[i].state, eventMapper) map(data.rooms[i].state, eventMapper)
); );
@@ -777,7 +809,7 @@ var init = function(exports){
roomInitialSync: function(roomId, limit, callback) { roomInitialSync: function(roomId, limit, callback) {
if (isFunction(limit)) { callback = limit; limit = undefined; } if (isFunction(limit)) { callback = limit; limit = undefined; }
var path = encodeUri("/rooms/$roomId/initialSync", var path = encodeUri("/rooms/$roomId/initialSync",
{$roomId: roomId} {$roomId: roomId}
); );
if (!limit) { if (!limit) {
@@ -868,7 +900,7 @@ var init = function(exports){
addPushRule: function(scope, kind, ruleId, body, callback) { addPushRule: function(scope, kind, ruleId, body, callback) {
// NB. Scope not uri encoded because devices need the '/' // NB. Scope not uri encoded because devices need the '/'
var path = encodeUri("/pushrules/"+scope+"/$kind/$ruleId", { var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind, $kind: kind,
$ruleId: ruleId $ruleId: ruleId
}); });
@@ -879,7 +911,7 @@ var init = function(exports){
deletePushRule: function(scope, kind, ruleId, callback) { deletePushRule: function(scope, kind, ruleId, callback) {
// NB. Scope not uri encoded because devices need the '/' // NB. Scope not uri encoded because devices need the '/'
var path = encodeUri("/pushrules/"+scope+"/$kind/$ruleId", { var path = encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind, $kind: kind,
$ruleId: ruleId $ruleId: ruleId
}); });
@@ -947,15 +979,15 @@ var init = function(exports){
var path = encodeUri("/_matrix/media/v1/identicon/$ident", { var path = encodeUri("/_matrix/media/v1/identicon/$ident", {
$ident: identiconString $ident: identiconString
}); });
return this.credentials.baseUrl + path + return this.credentials.baseUrl + path +
(Object.keys(params).length === 0 ? "" : (Object.keys(params).length === 0 ? "" :
("?" + encodeParams(params))); ("?" + encodeParams(params)));
}, },
/** /**
* Get the content repository url with query parameters. * Get the content repository url with query parameters.
* @returns An object with a 'base', 'path' and 'params' for base URL, * @return {Object} An object with a 'base', 'path' and 'params' for
* path and query parameters respectively. * base URL, path and query parameters respectively.
*/ */
getContentUri: function() { getContentUri: function() {
var params = { var params = {
@@ -986,7 +1018,7 @@ var init = function(exports){
_doRequest: function(callback, method, path, params, data) { _doRequest: function(callback, method, path, params, data) {
var fullUri = this.credentials.baseUrl + CLIENT_PREFIX + path; var fullUri = this.credentials.baseUrl + CLIENT_PREFIX + path;
if (!params) { params = {}; } if (!params) { params = {}; }
return this._request(callback, method, fullUri, params, data); return this._request(callback, method, fullUri, params, data);
}, },
_doV2Request: function(callback, method, path, params, data) { _doV2Request: function(callback, method, path, params, data) {
@@ -1069,7 +1101,7 @@ var init = function(exports){
if (typeof exports === 'undefined') { if (typeof exports === 'undefined') {
// this assigns to "window" on browsers // this assigns to "window" on browsers
init(this.matrixcs={}); // jshint ignore:line init(this.matrixcs = {}); // jshint ignore:line
} }
else { else {
init(exports); init(exports);