diff --git a/client/views/app/messagePopupConfig.coffee b/client/views/app/messagePopupConfig.coffee index b541848a55e3..bdb81a854326 100644 --- a/client/views/app/messagePopupConfig.coffee +++ b/client/views/app/messagePopupConfig.coffee @@ -1,4 +1,4 @@ -@onlineUsers = new Mongo.Collection 'online-users' +@filteredUsers = new Mongo.Collection 'filtered-users' Template.messagePopupConfig.helpers popupUserConfig: -> @@ -6,14 +6,14 @@ Template.messagePopupConfig.helpers template = Template.instance() config = title: 'People' - collection: onlineUsers + collection: filteredUsers template: 'messagePopupUser' getInput: self.getInput textFilterDelay: 200 getFilter: (collection, filter) -> exp = new RegExp("^#{filter}", 'i') - Meteor.subscribe 'onlineUsers', filter - items = onlineUsers.find({$or: [{username: exp}, {name: exp}]}, {limit: 5}).fetch() + Meteor.subscribe 'filteredUsers', filter + items = filteredUsers.find({$or: [{username: exp}, {name: exp}]}, {limit: 5}).fetch() all = _id: '@all' diff --git a/packages/meteor-accounts-saml/saml_rocketchat.coffee b/packages/meteor-accounts-saml/saml_rocketchat.coffee index 25bd2c3e59fe..c75bddf38d9c 100644 --- a/packages/meteor-accounts-saml/saml_rocketchat.coffee +++ b/packages/meteor-accounts-saml/saml_rocketchat.coffee @@ -16,7 +16,7 @@ updateServices = -> Meteor.clearTimeout timer if timer? timer = Meteor.setTimeout -> - services = Settings.find({_id: /^(SAML_Custom_)[a-z]+$/i}).fetch() + services = RocketChat.models.Settings.find({_id: /^(SAML_Custom_)[a-z]+$/i}).fetch() Accounts.saml.settings.providers = [] @@ -27,26 +27,26 @@ updateServices = -> if service.value is true data = - buttonLabelText: Settings.findOne({_id: "#{service._id}_button_label_text"})?.value - buttonLabelColor: Settings.findOne({_id: "#{service._id}_button_label_color"})?.value - buttonColor: Settings.findOne({_id: "#{service._id}_button_color"})?.value + buttonLabelText: RocketChat.models.Settings.findOneById("#{service._id}_button_label_text")?.value + buttonLabelColor: RocketChat.models.Settings.findOneById("#{service._id}_button_label_color")?.value + buttonColor: RocketChat.models.Settings.findOneById("#{service._id}_button_color")?.value clientConfig: - provider: Settings.findOne({_id: "#{service._id}_provider"})?.value + provider: RocketChat.models.Settings.findOneById("#{service._id}_provider")?.value - Accounts.saml.settings.generateUsername = Settings.findOne({_id: "#{service._id}_generate_username"})?.value + Accounts.saml.settings.generateUsername = RocketChat.models.Settings.findOneById("#{service._id}_generate_username")?.value Accounts.saml.settings.providers.push provider: data.clientConfig.provider - entryPoint: Settings.findOne({_id: "#{service._id}_entry_point"})?.value - issuer: Settings.findOne({_id: "#{service._id}_issuer"})?.value - cert: Settings.findOne({_id: "#{service._id}_cert"})?.value + entryPoint: RocketChat.models.Settings.findOneById("#{service._id}_entry_point")?.value + issuer: RocketChat.models.Settings.findOneById("#{service._id}_issuer")?.value + cert: RocketChat.models.Settings.findOneById("#{service._id}_cert")?.value ServiceConfiguration.configurations.upsert {service: serviceName.toLowerCase()}, $set: data else ServiceConfiguration.configurations.remove {service: serviceName.toLowerCase()} , 2000 -Settings.find().observe +RocketChat.models.Settings.find().observe added: (record) -> if /^SAML_.+/.test record._id updateServices() @@ -60,5 +60,5 @@ Settings.find().observe updateServices() Meteor.startup -> - if not Settings.findOne({_id: /^(SAML_Custom)[a-z]+$/i})? + if not RocketChat.models.Settings.findOne({_id: /^(SAML_Custom)[a-z]+$/i})? Meteor.call 'addSamlService', 'default' diff --git a/packages/rocketchat-authorization/lib/permissions.coffee b/packages/rocketchat-authorization/client/collection.coffee similarity index 100% rename from packages/rocketchat-authorization/lib/permissions.coffee rename to packages/rocketchat-authorization/client/collection.coffee diff --git a/packages/rocketchat-authorization/package.js b/packages/rocketchat-authorization/package.js index bb32b2ac371e..d9cb3f715618 100644 --- a/packages/rocketchat-authorization/package.js +++ b/packages/rocketchat-authorization/package.js @@ -16,13 +16,15 @@ Package.onUse(function(api) { api.use('templating', 'client'); - api.addFiles('lib/permissions.coffee', ['server', 'client']); api.addFiles('lib/rocketchat.coffee', ['server','client']); + api.addFiles('client/collection.coffee', ['client']); api.addFiles('client/startup.coffee', ['client']); api.addFiles('client/hasPermission.coffee', ['client']); api.addFiles('client/hasRole.coffee', ['client']); + api.addFiles('server/models/Permissions.coffee', ['server']); + api.addFiles('server/functions/addUsersToRoles.coffee', ['server']); api.addFiles('server/functions/getPermissionsForRole.coffee', ['server']); api.addFiles('server/functions/getRoles.coffee', ['server']); diff --git a/packages/rocketchat-authorization/server/functions/getPermissionsForRole.coffee b/packages/rocketchat-authorization/server/functions/getPermissionsForRole.coffee index f19203fe8c87..aa68c55f26d0 100644 --- a/packages/rocketchat-authorization/server/functions/getPermissionsForRole.coffee +++ b/packages/rocketchat-authorization/server/functions/getPermissionsForRole.coffee @@ -6,4 +6,4 @@ RocketChat.authz.getPermissionsForRole = (roleName) -> unless roleName in roleNames throw new Meteor.Error 'invalid-role' - return _.pluck(ChatPermissions.find({roles : roleName }).fetch(), '_id') \ No newline at end of file + return _.pluck(RocketChat.models.Permissions.findByRole( roleName ).fetch(), '_id') diff --git a/packages/rocketchat-authorization/server/models/Permissions.coffee b/packages/rocketchat-authorization/server/models/Permissions.coffee new file mode 100644 index 000000000000..727b6b69eb3d --- /dev/null +++ b/packages/rocketchat-authorization/server/models/Permissions.coffee @@ -0,0 +1,11 @@ +RocketChat.models.Permissions = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'permissions' + + + # FIND + findByRole: (role, options) -> + query = + roles: role + + return @find query, options diff --git a/packages/rocketchat-authorization/server/publication.coffee b/packages/rocketchat-authorization/server/publication.coffee index 5cf4adef1df7..8f6e008e14c1 100644 --- a/packages/rocketchat-authorization/server/publication.coffee +++ b/packages/rocketchat-authorization/server/publication.coffee @@ -1,3 +1,3 @@ Meteor.publish 'permissions', -> console.log '[publish] permissions'.green - return ChatPermissions.find {} \ No newline at end of file + return RocketChat.models.Permissions.find {} diff --git a/packages/rocketchat-authorization/server/startup.coffee b/packages/rocketchat-authorization/server/startup.coffee index c684bd25d869..a8072af4f3c2 100644 --- a/packages/rocketchat-authorization/server/startup.coffee +++ b/packages/rocketchat-authorization/server/startup.coffee @@ -78,7 +78,7 @@ Meteor.startup -> roles = _.pluck(Roles.getAllRoles().fetch(), 'name'); for permission in permissions - ChatPermissions.upsert( permission._id, {$setOnInsert : permission }) + RocketChat.models.Permissions.upsert( permission._id, {$setOnInsert : permission }) for role in permission.roles unless role in roles Roles.createRole role diff --git a/packages/rocketchat-irc/irc.server.coffee b/packages/rocketchat-irc/irc.server.coffee index 8fda845e7b94..5ca927d8459f 100644 --- a/packages/rocketchat-irc/irc.server.coffee +++ b/packages/rocketchat-irc/irc.server.coffee @@ -160,7 +160,7 @@ class IrcClient console.log '[irc] onReceiveMessage -> '.yellow, 'source:', source, 'target:', target, 'content:', content source = @createUserWhenNotExist source if target[0] == '#' - room = ChatRoom.findOne {name: target.substring 1} + room = RocketChat.models.Rooms.findOneByName target.substring(1) else room = @createDirectRoomWhenNotExist(source, @user) @@ -178,7 +178,7 @@ class IrcClient onEndMemberList: (roomName) -> newMembers = @receiveMemberListBuf[roomName] console.log '[irc] onEndMemberList -> '.yellow, 'room:', roomName, 'members:', newMembers.join ',' - room = ChatRoom.findOne {name: roomName, t: 'c'} + room = RocketChat.models.Rooms.findOneByNameAndType roomName, 'c' unless room return @@ -189,17 +189,9 @@ class IrcClient for member in appendMembers @createUserWhenNotExist member - update = - $pull: - usernames: - $in: removeMembers - ChatRoom.update room._id, update - update = - $addToSet: - usernames: - $each: appendMembers - - ChatRoom.update room._id, update + RocketChat.models.Rooms.removeUsernamesById room._id, removeMembers + RocketChat.models.Rooms.addUsernamesById room._id, appendMembers + @isJoiningRoom = false roomName = @pendingJoinRoomBuf.shift() if roomName @@ -231,15 +223,12 @@ class IrcClient msg = "PRIVMSG #{target} :#{message.msg}\r\n" @sendRawMessage msg - initRoomList: () -> - roomsCursor = ChatRoom.find - usernames: - $in: [@user.username] - t: 'c' - , + initRoomList: -> + roomsCursor = RocketChat.models.Rooms.findByTypeContainigUsername 'c', @user.username, fields: name: 1 t: 1 + rooms = roomsCursor.fetch() for room in rooms @joinRoom(room) @@ -276,25 +265,17 @@ class IrcClient console.log '[irc] onAddMemberToRoom -> '.yellow, 'roomName:', roomName, 'member:', member @createUserWhenNotExist member - update = - $addToSet: - usernames: member - ChatRoom.update {name: roomName}, update + RocketChat.models.Rooms.addUsernameByName roomName, member onRemoveMemberFromRoom: (member, roomName)-> console.log '[irc] onRemoveMemberFromRoom -> '.yellow, 'roomName:', roomName, 'member:', member - update = - $pull: - usernames: member - ChatRoom.update {name: roomName}, update + RocketChat.models.Rooms.removeUsernameByName roomName, member onQuiteMember: (member) -> console.log '[irc] onQuiteMember ->'.yellow, 'username:', member - update = - $pull: - usernames: member - ChatRoom.update {}, update, {multi: true} + RocketChat.models.Rooms.removeUsernameFromAll member + Meteor.users.update {name: member}, $set: status: 'offline' @@ -319,7 +300,7 @@ class IrcClient console.log '[irc] createDirectRoomWhenNotExist -> '.yellow, 'source:', source, 'target:', target rid = [source._id, target._id].sort().join('') now = new Date() - ChatRoom.upsert + RocketChat.models.Rooms.upsert _id: rid , $set: @@ -328,7 +309,8 @@ class IrcClient t: 'd' msgs: 0 ts: now - ChatSubscription.upsert + + RocketChat.models.Subscriptions.upsert rid: rid $and: [{'u._id': target._id}] , @@ -373,7 +355,7 @@ class IrcSender if ircReceiveMessageCache.get cacheKey return message - room = ChatRoom.findOne message.rid, { fields: { name: 1, usernames: 1, t: 1 } } + room = RocketChat.models.Rooms.findOneById message.rid, { fields: { name: 1, usernames: 1, t: 1 } } ircClient = IrcClient.getByUid message.u._id ircClient.sendMessage room, message return message diff --git a/packages/rocketchat-ldap/config_server.coffee b/packages/rocketchat-ldap/config_server.coffee index 97d28976f210..93c569f61e37 100644 --- a/packages/rocketchat-ldap/config_server.coffee +++ b/packages/rocketchat-ldap/config_server.coffee @@ -14,7 +14,7 @@ updateServices = -> Meteor.clearTimeout timer if timer? timer = Meteor.setTimeout -> - enable = Settings.findOne({_id: 'LDAP_Enable', value: true}) + enable = RocketChat.models.Settings.findOne({_id: 'LDAP_Enable', value: true}) if enable? console.log "Enabling LDAP".blue @@ -29,7 +29,7 @@ updateServices = -> LDAP_DEFAULTS.bindSearch = undefined , 2000 -Settings.find().observe +RocketChat.models.Settings.find().observe added: (record) -> if /^LDAP_.+/.test record._id updateServices() diff --git a/packages/rocketchat-ldap/package.js b/packages/rocketchat-ldap/package.js index 0d510d5fdff0..83d74fcf59f2 100644 --- a/packages/rocketchat-ldap/package.js +++ b/packages/rocketchat-ldap/package.js @@ -6,7 +6,7 @@ Package.describe({ }); Npm.depends({ - ldapjs: "0.7.1", + ldapjs: "0.7.1", }); // Loads all i18n.json files into tapi18nFiles @@ -22,6 +22,7 @@ Package.onUse(function(api) { api.versionsFrom('1.0.3.1'); // Commom + api.use('rocketchat:lib@0.0.1'); api.use('tap:i18n@1.5.1'); api.use('yasaricli:slugify'); api.use('coffeescript'); @@ -43,7 +44,7 @@ Package.onUse(function(api) { api.addFiles('config_server.coffee', 'server'); api.addFiles(tapi18nFiles); - + api.export('LDAP', 'server'); api.export('LDAP_DEFAULTS', 'server'); api.export('MeteorWrapperLdapjs'); diff --git a/packages/rocketchat-lib/lib/core.coffee b/packages/rocketchat-lib/lib/core.coffee index 4004fac11be9..ab59434d54c7 100644 --- a/packages/rocketchat-lib/lib/core.coffee +++ b/packages/rocketchat-lib/lib/core.coffee @@ -3,4 +3,5 @@ # @namespace RocketChat ### -RocketChat = {} +RocketChat = + models: {} diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 0e7854b0ad52..71da41c68a13 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -7,13 +7,15 @@ Package.describe({ Package.onUse(function(api) { api.versionsFrom('1.0'); - + api.use('reactive-var'); api.use('reactive-dict'); api.use('coffeescript'); api.use('random'); + api.use('check'); api.use('underscore'); api.use('underscorestring:underscore.string'); + api.use('monbro:mongodb-mapreduce-aggregation@1.0.1'); // TAPi18n api.use('templating', 'client'); @@ -28,14 +30,33 @@ Package.onUse(function(api) { api.imply('tap:i18n'); api.addFiles("package-tap.i18n", ["client", "server"]); + // COMMON api.addFiles('lib/core.coffee'); api.addFiles('lib/callbacks.coffee'); api.addFiles('lib/slashCommand.coffee'); - api.addFiles('settings/lib/settings.coffee'); + // MODELS SERVER + api.addFiles('server/models/_Base.coffee', 'server'); + api.addFiles('server/models/Users.coffee', 'server'); + api.addFiles('server/models/Subscriptions.coffee', 'server'); + api.addFiles('server/models/Rooms.coffee', 'server'); + api.addFiles('server/models/Messages.coffee', 'server'); + api.addFiles('server/models/Reports.coffee', 'server'); + + // Settings api.addFiles('settings/lib/rocketchat.coffee'); + api.addFiles('settings/server/models/Settings.coffee', 'server'); + api.addFiles('settings/server/methods.coffee', 'server'); + api.addFiles('settings/server/publication.coffee', 'server'); + api.addFiles('settings/server/startup.coffee', 'server'); + api.addFiles('settings/server/updateServices.coffee', 'server'); + api.addFiles('settings/server/addOAuthService.coffee', 'server'); + + api.addFiles('settings/lib/settings.coffee'); + + // CLIENT api.addFiles('client/Notifications.coffee', 'client'); api.addFiles('client/TabBar.coffee', 'client'); @@ -58,13 +79,6 @@ Package.onUse(function(api) { api.addFiles('server/Notifications.coffee', 'server'); - // Settings - api.addFiles('settings/server/methods.coffee', 'server'); - api.addFiles('settings/server/publication.coffee', 'server'); - api.addFiles('settings/server/startup.coffee', 'server'); - api.addFiles('settings/server/updateServices.coffee', 'server'); - api.addFiles('settings/server/addOAuthService.coffee', 'server'); - api.addFiles('server/cdn.coffee', 'server'); // TAPi18n -- needs to be added last diff --git a/packages/rocketchat-lib/server/Notifications.coffee b/packages/rocketchat-lib/server/Notifications.coffee index 24a2c7b95e12..9831d26c4436 100644 --- a/packages/rocketchat-lib/server/Notifications.coffee +++ b/packages/rocketchat-lib/server/Notifications.coffee @@ -19,7 +19,7 @@ RocketChat.Notifications = new class roomId = eventName.split('/')[0] user = Meteor.users.findOne @userId, {fields: {username: 1}} - return ChatRoom.findOne({_id: roomId, usernames: user.username}, {fields: {_id: 1}})? + return RocketChat.models.Rooms.findOneByIdContainigUsername(roomId, user.username, {fields: {_id: 1}})? @streamUser.permissions.write -> return @userId? @streamUser.permissions.read (eventName) -> diff --git a/packages/rocketchat-lib/server/functions/setUsername.coffee b/packages/rocketchat-lib/server/functions/setUsername.coffee index aed65e1e30ae..664b48e9e854 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.coffee +++ b/packages/rocketchat-lib/server/functions/setUsername.coffee @@ -10,7 +10,7 @@ RocketChat.setUsername = (user, username) -> if user.username is username return user - # Check username availability + # Check username availability unless RocketChat.checkUsernameAvailability username return false @@ -18,17 +18,17 @@ RocketChat.setUsername = (user, username) -> # Username is available; if coming from old username, update all references if previousUsername - ChatMessage.update { "u._id": user._id }, { $set: { "u.username": username } }, { multi: true } - - ChatMessage.find({ "mentions.username": previousUsername }).forEach (msg) -> + RocketChat.models.Messages.updateAllUsernamesByUserId user._id, username + + RocketChat.models.Messages.findByMention(previousUsername).forEach (msg) -> updatedMsg = msg.msg.replace(new RegExp("@#{previousUsername}", "ig"), "@#{username}") - ChatMessage.update { _id: msg._id, "mentions.username": previousUsername }, { $set: { "mentions.$.username": username, "msg": updatedMsg } } + RocketChat.models.Messages.updateUsernameAndMessageOfMentionByIdAndOldUsername msg._id, previousUsername, username, updatedMsg - ChatRoom.update { usernames: previousUsername }, { $set: { "usernames.$": username } }, { multi: true } - ChatRoom.update { "u._id": user._id }, { $set: { "u.username": username } }, { multi: true } + RocketChat.models.Rooms.replaceUsername previousUsername, username + RocketChat.models.Rooms.replaceUsernameOfUserByUserId user._id, username - ChatSubscription.update { "u._id": user._id }, { $set: { "u.username": username } }, { multi: true } - ChatSubscription.update { name: previousUsername, t: "d" }, { $set: { name: username } }, { multi: true } + RocketChat.models.Subscriptions.setUserUsernameByUserId user._id, username + RocketChat.models.Subscriptions.setNameForDirectRoomsWithOldName previousUsername, username # Set new username Meteor.users.update { _id: user._id }, { $set: { username: username } } diff --git a/packages/rocketchat-lib/server/methods/joinDefaultChannels.coffee b/packages/rocketchat-lib/server/methods/joinDefaultChannels.coffee index 7e90c213ba4a..6a78d7197df4 100644 --- a/packages/rocketchat-lib/server/methods/joinDefaultChannels.coffee +++ b/packages/rocketchat-lib/server/methods/joinDefaultChannels.coffee @@ -9,35 +9,19 @@ Meteor.methods RocketChat.callbacks.run 'beforeJoinDefaultChannels', user - ChatRoom.find({default: true, t: {$in: ['c', 'p']}}).forEach (room) -> + RocketChat.models.Rooms.findByDefaultAndTypes(true, ['c', 'p']).forEach (room) -> # put user in default rooms - ChatRoom.update room._id, - $addToSet: - usernames: user.username + RocketChat.models.Rooms.addUsernameById room._id, user.username - if not ChatSubscription.findOne(rid: room._id, 'u._id': user._id)? + if not RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)? # Add a subscription to this user - ChatSubscription.insert - rid: room._id - name: room.name + RocketChat.models.Subscriptions.createWithRoomAndUser room, user, ts: new Date() - t: room.t - f: false open: true alert: true unread: 1 - u: - _id: user._id - username: user.username # Insert user joined message - ChatMessage.insert - rid: room._id - ts: new Date() - t: 'uj' - msg: '' - u: - _id: user._id - username: user.username + RocketChat.models.Messages.createUserJoinWithRoomIdAndUser room._id, user diff --git a/packages/rocketchat-lib/server/models/Messages.coffee b/packages/rocketchat-lib/server/models/Messages.coffee new file mode 100644 index 000000000000..478707a9b632 --- /dev/null +++ b/packages/rocketchat-lib/server/models/Messages.coffee @@ -0,0 +1,216 @@ +RocketChat.models.Messages = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'message' + + @tryEnsureIndex { 'rid': 1, 'ts': 1 } + @tryEnsureIndex { 'ets': 1 }, { sparse: 1 } + @tryEnsureIndex { 'rid': 1, 't': 1, 'u._id': 1 } + @tryEnsureIndex { 'expireAt': 1 }, { expireAfterSeconds: 0 } + @tryEnsureIndex { 'msg': 'text' } + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options + + # FIND + findByMention: (username, options) -> + query = + "mentions.username": username + + return @find query, options + + findVisibleByRoomId: (roomId, options) -> + query = + _hidden: + $ne: true + rid: roomId + + return @find query, options + + findInvisibleByRoomId: (roomId, options) -> + query = + _hidden: true + rid: roomId + + return @find query, options + + findVisibleByRoomIdAfterTimestamp: (roomId, timestamp, options) -> + query = + _hidden: + $ne: true + rid: roomId + ts: + $gt: timestamp + + return @find query, options + + findVisibleByRoomIdBeforeTimestamp: (roomId, timestamp, options) -> + query = + _hidden: + $ne: true + rid: roomId + ts: + $lt: timestamp + + return @find query, options + + findVisibleByRoomIdBetweenTimestamps: (roomId, afterTimestamp, beforeTimestamp, options) -> + query = + _hidden: + $ne: true + rid: roomId + ts: + $gt: afterTimestamp + $lt: beforeTimestamp + + return @find query, options + + findVisibleCreatedOrEditedAfterTimestamp: (timestamp, options) -> + query = + _hidden: { $ne: true } + $or: [ + ts: + $gt: timestamp + , + ets: + $gt: timestamp + ] + + return @find query, options + + cloneAndSaveAsHistoryById: (_id) -> + record = @findOneById _id + record._hidden = true + record.parent = record._id + record.ets = new Date() + delete record._id + + return @insert record + + + # UPDATE + setHiddenById: (_id, hidden=true) -> + query = + _id: _id + + update = + $set: + _hidden: hidden + + return @update query, update + + setAsDeletedById: (_id) -> + query = + _id: _id + + update = + $set: + msg: '' + t: 'rm' + ets: new Date() + + return @update query, update + + setPinnedByIdAndUserId: (_id, userId, pinned=true) -> + query = + _id: _id + 'u._id': userId + + update = + $set: + pinned: pinned + pts: new Date + + return @update query, update + + setUrlsById: (_id, urls) -> + query = + _id: _id + + update = + $set: + urls: urls + + return @update query, update + + updateAllUsernamesByUserId: (userId, username) -> + query = + 'u._id': userId + + update = + $set: + "u.username": username + + return @update query, update, { multi: true } + + updateUsernameAndMessageOfMentionByIdAndOldUsername: (_id, oldUsername, newUsername, newMessage) -> + query = + _id: _id + "mentions.username": oldUsername + + update = + $set: + "mentions.$.username": newUsername + "msg": newMessage + + return @update query, update + + + # INSERT + createWithTypeRoomIdMessageAndUser: (type, roomId, message, user, extraData) -> + record = + t: type + rid: roomId + ts: new Date + msg: message + u: + _id: user._id + username: user.username + + _.extend record, extraData + + record._id = @insert record + return record + + createUserJoinWithRoomIdAndUser: (roomId, user, extraData) -> + message = user.name or user.username + return @createWithTypeRoomIdMessageAndUser 'uj', roomId, message, user, extraData + + createUserLeaveWithRoomIdAndUser: (roomId, user, extraData) -> + message = user.name or user.username + return @createWithTypeRoomIdMessageAndUser 'ul', roomId, message, user, extraData + + createUserRemovedWithRoomIdAndUser: (roomId, user, extraData) -> + message = user.name or user.username + return @createWithTypeRoomIdMessageAndUser 'ru', roomId, message, user, extraData + + createUserAddedWithRoomIdAndUser: (roomId, user, extraData) -> + message = user.name or user.username + return @createWithTypeRoomIdMessageAndUser 'au', roomId, message, user, extraData + + createRoomRenamedWithRoomIdRoomNameAndUser: (roomId, roomName, user, extraData) -> + return @createWithTypeRoomIdMessageAndUser 'r', roomId, roomName, user, extraData + + + # REMOVE + removeById: (_id) -> + query = + _id: _id + + return @remove query + + removeByRoomId: (roomId) -> + query = + rid: roomId + + return @remove query + + removeByUserId: (userId) -> + query = + "u._id": userId + + return @remove query diff --git a/packages/rocketchat-lib/server/models/Reports.coffee b/packages/rocketchat-lib/server/models/Reports.coffee new file mode 100644 index 000000000000..edadbd9bb8fb --- /dev/null +++ b/packages/rocketchat-lib/server/models/Reports.coffee @@ -0,0 +1,17 @@ +RocketChat.models.Reports = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'reports' + + + # INSERT + createWithMessageDescriptionAndUserId: (message, description, userId, extraData) -> + record = + message: message + description: description + ts: new Date() + userId: userId + + _.extend record, extraData + + record._id = @insert record + return record diff --git a/packages/rocketchat-lib/server/models/Rooms.coffee b/packages/rocketchat-lib/server/models/Rooms.coffee new file mode 100644 index 000000000000..e31711c7f4c1 --- /dev/null +++ b/packages/rocketchat-lib/server/models/Rooms.coffee @@ -0,0 +1,337 @@ +RocketChat.models.Rooms = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'room' + + @tryEnsureIndex { 'name': 1 }, { unique: 1, sparse: 1 } + @tryEnsureIndex { 'u._id': 1 } + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options + + findOneByName: (name, options) -> + query = + name: name + + return @findOne query, options + + findOneByNameAndType: (name, type, options) -> + query = + name: name + t: type + + return @findOne query, options + + findOneByIdContainigUsername: (_id, username, options) -> + query = + _id: _id + usernames: username + + return @findOne query, options + + findOneByNameAndTypeNotContainigUsername: (name, type, username, options) -> + query = + name: name + t: type + usernames: + $ne: username + + return @findOne query, options + + + # FIND + findByType: (type, options) -> + query = + t: type + + return @find query, options + + findByTypes: (types, options) -> + query = + t: + $in: types + + return @find query, options + + findByUserId: (userId, options) -> + query = + "u._id": userId + + return @find query, options + + findByNameContaining: (name, options) -> + nameRegex = new RegExp name, "i" + + query = + $or: [ + name: nameRegex + , + t: 'd' + usernames: nameRegex + ] + + return @find query, options + + findByNameContainingAndTypes: (name, types, options) -> + nameRegex = new RegExp name, "i" + + query = + t: + $in: types + $or: [ + name: nameRegex + , + t: 'd' + usernames: nameRegex + ] + + return @find query, options + + findByDefaultAndTypes: (defaultValue, types, options) -> + query = + default: defaultValue + t: + $in: types + + return @find query, options + + findByTypeContainigUsername: (type, username, options) -> + query = + t: type + usernames: username + + return @find query, options + + findByTypesAndNotUserIdContainingUsername: (types, userId, username, options) -> + query = + t: + $in: types + uid: + $ne: userId + usernames: username + + return @find query, options + + findByContainigUsername: (username, options) -> + query = + usernames: username + + return @find query, options + + findByTypeAndName: (type, name, options) -> + query = + t: type + name: name + + return @find query, options + + findByTypeAndNameContainigUsername: (type, name, username, options) -> + query = + t: type + name: name + usernames: username + + return @find query, options + + findByVisitorToken: (visitorToken, options) -> + query = + "v.token": visitorToken + + return @find query, options + + + # UPDATE + archiveById: (_id) -> + query = + _id: _id + + update = + $set: + archived: true + + return @update query, update + + unarchiveById: (_id) -> + query = + _id: _id + + update = + $set: + archived: false + + return @update query, update + + addUsernameById: (_id, username) -> + query = + _id: _id + + update = + $addToSet: + usernames: username + + return @update query, update + + addUsernamesById: (_id, usernames) -> + query = + _id: _id + + update = + $addToSet: + usernames: + $each: usernames + + return @update query, update + + addUsernameByName: (name, username) -> + query = + name: name + + update = + $addToSet: + usernames: username + + return @update query, update + + removeUsernameById: (_id, username) -> + query = + _id: _id + + update = + $pull: + usernames: username + + return @update query, update + + removeUsernamesById: (_id, usernames) -> + query = + _id: _id + + update = + $pull: + usernames: + $in: usernames + + return @update query, update + + removeUsernameFromAll: (username) -> + query = {} + + update = + $pull: + usernames: username + + return @update query, update, { multi: true } + + removeUsernameByName: (name, username) -> + query = + name: name + + update = + $pull: + usernames: username + + return @update query, update + + setNameById: (_id, name) -> + query = + _id: _id + + update = + $set: + name: name + + return @update query, update + + incUnreadAndSetLastMessageTimestampById: (_id, inc=1, lastMessageTimestamp) -> + query = + _id: _id + + update = + $set: + lm: lastMessageTimestamp + $inc: + msgs: inc + + return @update query, update + + replaceUsername: (previousUsername, username) -> + query = + usernames: previousUsername + + update = + $set: + "usernames.$": username + + return @update query, update, { multi: true } + + replaceUsernameOfUserByUserId: (userId, username) -> + query = + "u._id": userId + + update = + $set: + "u.username": username + + return @update query, update, { multi: true } + + setUserById: (_id, user) -> + query = + _id: _id + + update = + $set: + u: + _id: user._id + username: user.username + + return @update query, update + + + # INSERT + createWithTypeNameUserAndUsernames: (type, name, user, usernames, extraData) -> + room = + t: type + name: name + usernames: usernames + msgs: 0 + u: + _id: user._id + username: user.username + + _.extend room, extraData + + room._id = @insert room + return room + + createWithIdTypeAndName: (_id, type, name, extraData) -> + room = + _id: _id + ts: new Date() + t: type + name: name + usernames: [] + msgs: 0 + + _.extend room, extraData + + @insert room + return room + + + # REMOVE + removeById: (_id) -> + query = + _id: _id + + return @remove query + + removeByTypeContainingUsername: (type, username) -> + query = + t: type + username: username + + return @remove query diff --git a/packages/rocketchat-lib/server/models/Subscriptions.coffee b/packages/rocketchat-lib/server/models/Subscriptions.coffee new file mode 100644 index 000000000000..ed7adbb93cee --- /dev/null +++ b/packages/rocketchat-lib/server/models/Subscriptions.coffee @@ -0,0 +1,190 @@ +RocketChat.models.Subscriptions = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'subscription' + + @tryEnsureIndex { 'rid': 1, 'u._id': 1 }, { unique: 1 } + @tryEnsureIndex { 'u._id': 1, 'name': 1, 't': 1 }, { unique: 1 } + @tryEnsureIndex { 'open': 1 } + @tryEnsureIndex { 'alert': 1 } + @tryEnsureIndex { 'unread': 1 } + @tryEnsureIndex { 'ts': 1 } + + + # FIND ONE + findOneByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + "u._id": userId + + return @findOne query + + # FIND + findByUserId: (userId, options) -> + query = + "u._id": userId + + return @find query, options + + + # UPDATE + archiveByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + alert: false + open: false + archived: true + + return @update query, update + + unarchiveByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + alert: false + open: false + archived: false + + return @update query, update + + hideByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + alert: false + open: false + + return @update query, update + + openByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + open: true + + return @update query, update + + setAsReadByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + open: true + alert: false + unread: 0 + ls: new Date + + return @update query, update + + setFavoriteByRoomIdAndUserId: (roomId, userId, favorite=true) -> + query = + rid: roomId + 'u._id': userId + + update = + $set: + f: favorite + + return @update query, update + + updateNameByRoomId: (roomId, name) -> + query = + rid: roomId + + update = + $set: + name: name + alert: true + + return @update query, update, { multi: true } + + setUserUsernameByUserId: (userId, username) -> + query = + "u._id": userId + + update = + $set: + "u.username": username + + return @update query, update, { multi: true } + + setNameForDirectRoomsWithOldName: (oldName, name) -> + query = + name: oldName + t: "d" + + update = + $set: + name: name + + return @update query, update, { multi: true } + + incUnreadOfDirectForRoomIdExcludingUserId: (roomId, userId, inc=1) -> + query = + rid: roomId + t: 'd' + 'u._id': + $ne: userId + + update = + $set: + alert: true + open: true + $inc: + unread: inc + + return @update query, update, { multi: true } + + + # INSERT + createWithRoomAndUser: (room, user, extraData) -> + subscription = + open: false + alert: false + unread: 0 + ts: room.ts + rid: room._id + name: room.name + t: room.t + u: + _id: user._id + username: user.username + + _.extend subscription, extraData + + return @insert subscription + + + # REMOVE + removeByUserId: (userId) -> + query = + "u._id": userId + + return @remove query + + removeByRoomId: (roomId) -> + query = + rid: roomId + + return @remove query + + removeByRoomIdAndUserId: (roomId, userId) -> + query = + rid: roomId + "u._id": userId + + return @remove query diff --git a/packages/rocketchat-lib/server/models/Users.coffee b/packages/rocketchat-lib/server/models/Users.coffee new file mode 100644 index 000000000000..6945de54d328 --- /dev/null +++ b/packages/rocketchat-lib/server/models/Users.coffee @@ -0,0 +1,199 @@ +RocketChat.models.Users = new class extends RocketChat.models._Base + constructor: -> + @model = Meteor.users + + + # FIND ONE + findOneById: (_id, options) -> + return @findOne _id, options + + findOneByUsername: (username, options) -> + query = + username: username + + return @findOne query, options + + findOneByEmailAddress: (emailAddress, options) -> + query = + 'email.address': emailAddress + + return @findOne query, options + + findOneByVerifiedEmailAddress: (emailAddress, options) -> + query = + emails: + $elemMatch: + address: emailAddress + verified: true + + return @findOne query, options + + findOneAdmin: (admin, options) -> + query = + admin: admin + + return @findOne query, options + + + # FIND + findUsersNotOffline: (options) -> + query = + username: + $exists: 1 + status: + $in: ['online', 'away', 'busy'] + + return @find query, options + + + findByUsername: (username, options) -> + query = + username: username + + return @find query, options + + findUsersByNameOrUsername: (nameOrUsername, options) -> + query = + username: + $exists: 1 + + $or: [ + {name: nameOrUsername} + {username: nameOrUsername} + ] + + return @find query, options + + findByUsernameNameOrEmailAddress: (usernameNameOrEmailAddress, options) -> + query = + $or: [ + {name: usernameNameOrEmailAddress} + {username: usernameNameOrEmailAddress} + {'emails.address': usernameNameOrEmailAddress} + ] + + return @find query, options + + + # UPDATE + updateLastLoginById: (_id) -> + update = + $set: + lastLogin: new Date + + return @update _id, update + + setServiceId: (_id, serviceName, serviceId) -> + update = + $set: {} + + serviceIdKey = "services.#{serviceName}.id" + update.$set[serviceIdKey] = serviceData.id + + return @update _id, update + + setUsername: (_id, username) -> + update = + $set: username: username + + return @update _id, update + + setName: (_id, name) -> + update = + $set: + name: name + + return @update _id, update + + setAvatarOrigin: (_id, origin) -> + update = + $set: + avatarOrigin: origin + + return @update _id, update + + unsetAvatarOrigin: (_id) -> + update = + $unset: + avatarOrigin: 1 + + return @update _id, update + + setUserActive: (_id, active=true) -> + update = + $set: + active: active + + return @update _id, update + + setAllUsersActive: (active) -> + update = + $set: + active: active + + return @update {}, update, { multi: true } + + unsetLoginTokens: (_id) -> + update = + $set: + "services.resume.loginTokens" : [] + + return @update _id, update + + setLanguage: (_id, language) -> + update = + $set: + language: language + + return @update _id, update + + setProfile: (_id, profile) -> + update = + $set: + "settings.profile": profile + + return @update _id, update + + setPreferences: (_id, preferences) -> + update = + $set: + "settings.preferences": preferences + + return @update _id, update + + setUtcOffset: (_id, utcOffset) -> + query = + _id: _id + utcOffset: + $ne: utcOffset + + update = + $set: + utcOffset: utcOffset + + return @update query, update + + + # INSERT + create: (data) -> + user = + createdAt: new Date + avatarOrigin: 'none' + + _.extend user, data + + return @insert user + + + # REMOVE + removeById: (_id) -> + return @remove _id + + removeByUnverifiedEmail: (email) -> + query = + emails: + $elemMatch: + address: email + verified: false + + return @remove query diff --git a/packages/rocketchat-lib/server/models/_Base.coffee b/packages/rocketchat-lib/server/models/_Base.coffee new file mode 100644 index 000000000000..c3d5e7f3b0cf --- /dev/null +++ b/packages/rocketchat-lib/server/models/_Base.coffee @@ -0,0 +1,50 @@ +RocketChat.models._Base = class + _baseName: -> + return 'rocketchat_' + + _initModel: (name) -> + check name, String + + @model = new Meteor.Collection @_baseName() + name + + find: -> + return @model.find.apply @model, arguments + + findOne: -> + return @model.findOne.apply @model, arguments + + insert: -> + return @model.insert.apply @model, arguments + + update: -> + return @model.update.apply @model, arguments + + upsert: -> + return @model.upsert.apply @model, arguments + + remove: -> + return @model.remove.apply @model, arguments + + allow: -> + return @model.allow.apply @model, arguments + + deny: -> + return @model.allow.apply @model, arguments + + ensureIndex: -> + return @model._ensureIndex.apply @model, arguments + + dropIndex: -> + return @model._dropIndex.apply @model, arguments + + tryEnsureIndex: -> + try + return @ensureIndex.apply @, arguments + catch e + console.log e + + tryDropIndex: -> + try + return @dropIndex.apply @, arguments + catch e + console.log e diff --git a/packages/rocketchat-lib/server/sendMessage.coffee b/packages/rocketchat-lib/server/sendMessage.coffee index b3a7625c410e..a60a2aab43ff 100644 --- a/packages/rocketchat-lib/server/sendMessage.coffee +++ b/packages/rocketchat-lib/server/sendMessage.coffee @@ -16,9 +16,9 @@ RocketChat.sendMessage = (user, message, room, options) -> message = RocketChat.callbacks.run 'beforeSaveMessage', message if message._id? and options?.upsert is true - ChatMessage.upsert {_id: message._id}, message + RocketChat.models.Messages.upsert {_id: message._id}, message else - message._id = ChatMessage.insert message + message._id = RocketChat.models.Messages.insert message ### Defer other updates as their return is not interesting to the user @@ -35,17 +35,7 @@ RocketChat.sendMessage = (user, message, room, options) -> Update all the room activity tracker fields ### Meteor.defer -> - - ChatRoom.update - # only subscriptions to the same room - _id: message.rid - , - # update the last message timestamp - $set: - lm: message.ts - # increment the messages counter - $inc: - msgs: 1 + RocketChat.models.Rooms.incUnreadAndSetLastMessageTimestampById message.rid, 1, message.ts ### Increment unread couter if direct messages @@ -57,23 +47,7 @@ RocketChat.sendMessage = (user, message, room, options) -> ### Update the other subscriptions ### - ChatSubscription.update - # only subscriptions to the same room - rid: message.rid - # only direct messages subscriptions - t: 'd' - # not the msg owner - 'u._id': - $ne: message.u._id - , - $set: - # alert de user - alert: true - # open the room for the user - open: true - # increment unread couter - $inc: - unread: 1 + RocketChat.models.Subscriptions.incUnreadOfDirectForRoomIdExcludingUserId message.rid, message.u._id, 1 userOfMention = Meteor.users.findOne({_id: message.rid.replace(message.u._id, '')}, {fields: {username: 1, statusConnection: 1}}) if userOfMention? @@ -121,28 +95,12 @@ RocketChat.sendMessage = (user, message, room, options) -> Update all other subscriptions of mentioned users to alert their owners and incrementing the unread counter for mentions and direct messages ### - query = - # only subscriptions to the same room - rid: message.rid - if mentionIds.indexOf('all') > -1 # all users except sender if mention is for all - query['u._id'] = $ne: user._id + RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId message.rid, user._id, 1 else # the mentioned user if mention isn't for all - query['u._id'] = $in: mentionIds - - ChatSubscription.update query, - $set: - # alert de user - alert: true - # open the room for the user - open: true - # increment unread couter - $inc: - unread: 1 - , - multi: true + RocketChat.models.Subscriptions.incUnreadForRoomIdAndUserIds message.rid, mentionIds, 1 query = statusConnection: {$ne: 'online'} @@ -191,22 +149,6 @@ RocketChat.sendMessage = (user, message, room, options) -> Update all other subscriptions to alert their owners but witout incrementing the unread counter, as it is only for mentions and direct messages ### - ChatSubscription.update - # only subscriptions to the same room - rid: message.rid - # only the ones that have not been alerted yet - alert: { $ne: true } - # not the msg owner - 'u._id': - $ne: message.u._id - , - $set: - # alert de user - alert: true - # open the room for the user - open: true - , - # make sure we alert all matching subscription - multi: true + RocketChat.models.Subscriptions.setAlertForRoomIdExcludingUserId message.rid, message.u._id, true return message diff --git a/packages/rocketchat-lib/settings/lib/settings.coffee b/packages/rocketchat-lib/settings/lib/settings.coffee index 7fca2088cb07..cc97e7623a29 100644 --- a/packages/rocketchat-lib/settings/lib/settings.coffee +++ b/packages/rocketchat-lib/settings/lib/settings.coffee @@ -1,4 +1,7 @@ -@Settings = new Meteor.Collection 'rocketchat_settings' +if Meteor.isClient is true + @Settings = Settings = new Meteor.Collection 'rocketchat_settings' +else + Settings = RocketChat.models.Settings Settings.find().observe added: (record) -> diff --git a/packages/rocketchat-lib/settings/server/addOAuthService.coffee b/packages/rocketchat-lib/settings/server/addOAuthService.coffee index 479877939ac4..fb95f2e4d517 100644 --- a/packages/rocketchat-lib/settings/server/addOAuthService.coffee +++ b/packages/rocketchat-lib/settings/server/addOAuthService.coffee @@ -30,13 +30,13 @@ Meteor.methods throw new Meteor.Error 'not-authorized', '[methods] addOAuthService -> Not authorized' name = s.capitalize(name) - Settings.remove _id: "Accounts_OAuth_Custom_#{name}" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_url" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_token_path" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_identity_path" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_authorize_path" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_id" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_secret" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_button_label_text" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_button_label_color" - Settings.remove _id: "Accounts_OAuth_Custom_#{name}_button_color" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_url" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_token_path" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_identity_path" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_authorize_path" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_id" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_secret" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_button_label_text" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_button_label_color" + RocketChat.settings.removeById "Accounts_OAuth_Custom_#{name}_button_color" diff --git a/packages/rocketchat-lib/settings/server/methods.coffee b/packages/rocketchat-lib/settings/server/methods.coffee index cf19272c96b4..deac2a9bac5f 100644 --- a/packages/rocketchat-lib/settings/server/methods.coffee +++ b/packages/rocketchat-lib/settings/server/methods.coffee @@ -1,5 +1,5 @@ ### -# Add a setting +# Add a setting # @param {String} _id # @param {Mixed} value # @param {Object} setting @@ -24,7 +24,7 @@ RocketChat.settings.add = (_id, value, options = {}) -> updateSettings.section = options.section if options.section updateSettings.public = options.public if options.public - return Settings.upsert { _id: _id }, { $setOnInsert: { value: value }, $set: updateSettings } + return RocketChat.models.Settings.upsert { _id: _id }, { $setOnInsert: { value: value }, $set: updateSettings } ### # Add a setting group @@ -37,22 +37,37 @@ RocketChat.settings.addGroup = (_id, options = {}) -> # console.log '[functions] RocketChat.settings.addGroup -> '.green, 'arguments:', arguments - updateSettings = + updateSettings = i18nLabel: options.i18nLabel or _id i18nDescription: options.i18nDescription if options.i18nDescription? type: 'group' - - return Settings.upsert { _id: _id }, { $set: updateSettings } + + return RocketChat.models.Settings.upsert { _id: _id }, { $set: updateSettings } + + +### +# Remove a setting by id +# @param {String} _id +### + +RocketChat.settings.removeById = (_id) -> + if not _id + return false + + # console.log '[functions] RocketChat.settings.add -> '.green, 'arguments:', arguments + + return RocketChat.models.Settings.removeById _id + Meteor.methods saveSetting: (_id, value) -> console.log '[method] saveSetting', _id, value if Meteor.userId()? user = Meteor.users.findOne Meteor.userId() - + unless RocketChat.authz.hasPermission(Meteor.userId(), 'edit-privileged-setting') is true throw new Meteor.Error 503, 'Not authorized' # console.log "saveSetting -> ".green, _id, value - Settings.update { _id: _id }, { $set: { value: value } } - return true \ No newline at end of file + RocketChat.models.Settings.updateValueById _id, value + return true diff --git a/packages/rocketchat-lib/settings/server/models/Settings.coffee b/packages/rocketchat-lib/settings/server/models/Settings.coffee new file mode 100644 index 000000000000..282c9262b6b8 --- /dev/null +++ b/packages/rocketchat-lib/settings/server/models/Settings.coffee @@ -0,0 +1,54 @@ +RocketChat.models.Settings = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'settings' + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options + + + # FIND + findByRole: (role, options) -> + query = + role: role + + return @find query, options + + findPublic: (options) -> + query = + public: true + + return @find query, options + + + # UPDATE + updateValueById: (_id, value) -> + query = + _id: _id + + update = + $set: + value: value + + return @update query, update + + + # REMOVE + createWithIdAndValue: (_id, value) -> + record = + _id: _id + value: value + + return @insert record + + + # REMOVE + removeById: (_id) -> + query = + _id: _id + + return @remove query diff --git a/packages/rocketchat-lib/settings/server/publication.coffee b/packages/rocketchat-lib/settings/server/publication.coffee index d8577ba6a8bc..0c5a2b9161ee 100644 --- a/packages/rocketchat-lib/settings/server/publication.coffee +++ b/packages/rocketchat-lib/settings/server/publication.coffee @@ -1,5 +1,6 @@ Meteor.publish 'settings', (ids = []) -> console.log '[publish] settings'.green + filter = public: true @@ -7,7 +8,7 @@ Meteor.publish 'settings', (ids = []) -> filter._id = $in: ids - return Settings.find filter, { fields: _id: 1, value: 1 } + return RocketChat.models.Settings.find filter, { fields: _id: 1, value: 1 } Meteor.publish 'admin-settings', -> console.log '[publish] admin-settings'.green @@ -16,7 +17,7 @@ Meteor.publish 'admin-settings', -> return @ready() if RocketChat.authz.hasPermission( @userId, 'view-privileged-setting') - return Settings.find() + return RocketChat.models.Settings.find() else return @ready() diff --git a/packages/rocketchat-lib/settings/server/startup.coffee b/packages/rocketchat-lib/settings/server/startup.coffee index 8344d52cfe6e..bc87a272a9da 100644 --- a/packages/rocketchat-lib/settings/server/startup.coffee +++ b/packages/rocketchat-lib/settings/server/startup.coffee @@ -1,4 +1,8 @@ Meteor.startup -> + # Insert server unique id if it doesn't exist + if not RocketChat.models.Settings.findOneById 'uniqueID' + RocketChat.models.Settings.createWithIdAndValue 'uniqueID', Random.id() + RocketChat.settings.addGroup 'Accounts' RocketChat.settings.add 'Accounts_RegistrationRequired', true, { type: 'boolean', group: 'Accounts', public: true, section: 'Registration' } RocketChat.settings.add 'Accounts_EmailVerification', false, { type: 'boolean', group: 'Accounts', public: true, section: 'Registration' } @@ -45,7 +49,7 @@ Meteor.startup -> RocketChat.settings.add 'SMTP_Username', '', { type: 'string', group: 'SMTP' } RocketChat.settings.add 'SMTP_Password', '', { type: 'string', group: 'SMTP' } RocketChat.settings.add 'From_Email', 'no-reply@rocket.chat', { type: 'string', group: 'SMTP' } - + RocketChat.settings.add 'Invitation_Subject', 'You have been invited to Rocket.Chat', { type: 'string', group: 'SMTP', section: 'Invitation' } RocketChat.settings.add 'Invitation_HTML', '

You have been invited to

Rocket.Chat

Go to https://demo.rocket.chat and try the best open source chat solution available today!

', { type: 'string', multiline: true, group: 'SMTP', section: 'Invitation' } diff --git a/packages/rocketchat-lib/settings/server/updateServices.coffee b/packages/rocketchat-lib/settings/server/updateServices.coffee index 42c0098b7aa5..109a1363f583 100644 --- a/packages/rocketchat-lib/settings/server/updateServices.coffee +++ b/packages/rocketchat-lib/settings/server/updateServices.coffee @@ -3,7 +3,7 @@ updateServices = -> Meteor.clearTimeout timer if timer? timer = Meteor.setTimeout -> - services = Settings.find({_id: /^(Accounts_OAuth_|Accounts_OAuth_Custom_)[a-z]+$/i}).fetch() + services = RocketChat.models.Settings.find({_id: /^(Accounts_OAuth_|Accounts_OAuth_Custom_)[a-z]+$/i}).fetch() for service in services console.log "Updating login service #{service._id}".blue @@ -18,18 +18,18 @@ updateServices = -> if service.value is true data = - clientId: Settings.findOne({_id: "#{service._id}_id"})?.value - secret: Settings.findOne({_id: "#{service._id}_secret"})?.value + clientId: RocketChat.models.Settings.findOneById("#{service._id}_id")?.value + secret: RocketChat.models.Settings.findOneById("#{service._id}_secret")?.value if /Accounts_OAuth_Custom_/.test service._id data.custom = true - data.serverURL = Settings.findOne({_id: "#{service._id}_url"})?.value - data.tokenPath = Settings.findOne({_id: "#{service._id}_token_path"})?.value - data.identityPath = Settings.findOne({_id: "#{service._id}_identity_path"})?.value - data.authorizePath = Settings.findOne({_id: "#{service._id}_authorize_path"})?.value - data.buttonLabelText = Settings.findOne({_id: "#{service._id}_button_label_text"})?.value - data.buttonLabelColor = Settings.findOne({_id: "#{service._id}_button_label_color"})?.value - data.buttonColor = Settings.findOne({_id: "#{service._id}_button_color"})?.value + data.serverURL = RocketChat.models.Settings.findOneById("#{service._id}_url")?.value + data.tokenPath = RocketChat.models.Settings.findOneById("#{service._id}_token_path")?.value + data.identityPath = RocketChat.models.Settings.findOneById("#{service._id}_identity_path")?.value + data.authorizePath = RocketChat.models.Settings.findOneById("#{service._id}_authorize_path")?.value + data.buttonLabelText = RocketChat.models.Settings.findOneById("#{service._id}_button_label_text")?.value + data.buttonLabelColor = RocketChat.models.Settings.findOneById("#{service._id}_button_label_color")?.value + data.buttonColor = RocketChat.models.Settings.findOneById("#{service._id}_button_color")?.value new CustomOAuth serviceName.toLowerCase(), serverURL: data.serverURL tokenPath: data.tokenPath @@ -49,7 +49,7 @@ updateServices = -> ServiceConfiguration.configurations.remove {service: serviceName.toLowerCase()} , 2000 -Settings.find().observe +RocketChat.models.Settings.find().observe added: (record) -> if /^Accounts_OAuth_.+/.test record._id updateServices() diff --git a/packages/rocketchat-livechat/methods.coffee b/packages/rocketchat-livechat/methods.coffee index ab42d32e2e49..2edd1dd9c4f2 100644 --- a/packages/rocketchat-livechat/methods.coffee +++ b/packages/rocketchat-livechat/methods.coffee @@ -40,7 +40,7 @@ Meteor.methods guest = Meteor.users.findOne Meteor.userId(), fields: username: 1 - room = ChatRoom.findOne message.rid + room = RocketChat.models.Rooms.findOneById message.rid if not room? @@ -50,7 +50,7 @@ Meteor.methods unless operator throw new Meteor.Error 'no-operators', 'Sorry, no online operators' - ChatRoom.insert + RocketChat.models.Rooms.insert _id: message.rid name: guest.username msgs: 1 @@ -61,7 +61,7 @@ Meteor.methods v: token: message.token - ChatSubscription.insert + RocketChat.models.Subscriptions.insert rid: message.rid name: guest.username alert: true diff --git a/packages/rocketchat-livechat/publications.coffee b/packages/rocketchat-livechat/publications.coffee index bbf288286fad..e51b3841a7ef 100644 --- a/packages/rocketchat-livechat/publications.coffee +++ b/packages/rocketchat-livechat/publications.coffee @@ -1,7 +1,5 @@ Meteor.publish 'visitorRoom', (visitorToken) -> - return ChatRoom.find - "v.token": visitorToken - , + return RocketChat.models.Rooms.findByVisitorToken visitorToken, fields: name: 1 t: 1 diff --git a/packages/rocketchat-mentions/server.coffee b/packages/rocketchat-mentions/server.coffee index 781a3349b363..e51e5bed70c3 100644 --- a/packages/rocketchat-mentions/server.coffee +++ b/packages/rocketchat-mentions/server.coffee @@ -32,11 +32,11 @@ class MentionsServer channels = _.unique channels verifiedChannels = [] channels.forEach (mention) -> - verifiedChannel = ChatRoom.findOne({ name: mention, t: 'c' }, { fields: {_id: 1, name: 1 } }) + verifiedChannel = RocketChat.models.Rooms.findOneByNameAndType(mention, 'c', { fields: {_id: 1, name: 1 } }) verifiedChannels.push verifiedChannel if verifiedChannel? if verifiedChannels.length isnt 0 message.channels = verifiedChannels return message -RocketChat.callbacks.add 'beforeSaveMessage', MentionsServer \ No newline at end of file +RocketChat.callbacks.add 'beforeSaveMessage', MentionsServer diff --git a/packages/rocketchat-oembed/package.js b/packages/rocketchat-oembed/package.js index ceefbe83b725..fc9d4ff799cc 100644 --- a/packages/rocketchat-oembed/package.js +++ b/packages/rocketchat-oembed/package.js @@ -28,6 +28,7 @@ Package.onUse(function(api) { api.addFiles('client/oembedUrlWidget.coffee', 'client'); api.addFiles('server/server.coffee', 'server'); + api.addFiles('server/models/OEmbedCache.coffee', 'server'); api.export('OEmbed', 'server'); }); diff --git a/packages/rocketchat-oembed/server/models/OEmbedCache.coffee b/packages/rocketchat-oembed/server/models/OEmbedCache.coffee new file mode 100644 index 000000000000..c8555b42a0b4 --- /dev/null +++ b/packages/rocketchat-oembed/server/models/OEmbedCache.coffee @@ -0,0 +1,22 @@ +RocketChat.models.OEmbedCache = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'oembed_cache' + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options + + + # INSERT + createWithIdAndData: (_id: data) -> + record = + _id: _id + data: data + updatedAt: new Date + + record._id = @insert record + return record diff --git a/packages/rocketchat-oembed/server/server.coffee b/packages/rocketchat-oembed/server/server.coffee index 35329c51b82a..a998db74df8f 100644 --- a/packages/rocketchat-oembed/server/server.coffee +++ b/packages/rocketchat-oembed/server/server.coffee @@ -3,8 +3,7 @@ http = Npm.require('http') https = Npm.require('https') querystring = Npm.require('querystring') -OEmbed = - cache: new Meteor.Collection 'rocketchat_oembed_cache' +OEmbed = {} getUrlContent = (urlObj, redirectCount = 5, callback) -> if _.isString(urlObj) @@ -117,14 +116,14 @@ OEmbed.getUrlMeta = (url, withFragment) -> } OEmbed.getUrlMetaWithCache = (url, withFragment) -> - cache = OEmbed.cache.findOne {_id: url} + cache = RocketChat.models.OEmbedCache.findOneById url if cache? return cache.data data = OEmbed.getUrlMeta url, withFragment if data? - OEmbed.cache.insert {_id: url, data: data, updatedAt: new Date} + RocketChat.models.OEmbedCache.createWithIdAndData url, data return data @@ -167,7 +166,7 @@ OEmbed.RocketUrlParser = (message) -> changed = true if changed is true - ChatMessage.update {_id: message._id}, { $set: { urls: message.urls } } + RocketChat.models.Messages.setUrlsById message._id, message.urls return message diff --git a/packages/rocketchat-slashcommands-invite/invite.coffee b/packages/rocketchat-slashcommands-invite/invite.coffee index bcff940d8678..d11954234b03 100644 --- a/packages/rocketchat-slashcommands-invite/invite.coffee +++ b/packages/rocketchat-slashcommands-invite/invite.coffee @@ -24,10 +24,8 @@ else if not user? return - # verify the user isn't already in this room - room = ChatRoom.findOne({ _id: item.rid, usernames: { $nin: [ user.username ]} }) - - if not room? + # cancel if the user is already in this room + if RocketChat.models.Rooms.findOneByIdContainigUsername(item.rid, user.username)? return Meteor.runAsUser user._id, -> diff --git a/packages/rocketchat-slashcommands-join/join.coffee b/packages/rocketchat-slashcommands-join/join.coffee index 65b3700cc758..332e341a7237 100644 --- a/packages/rocketchat-slashcommands-join/join.coffee +++ b/packages/rocketchat-slashcommands-join/join.coffee @@ -20,7 +20,7 @@ else channel = channel.replace('#', '') user = Meteor.users.findOne Meteor.userId() - room = ChatRoom.findOne({ name: channel, t: 'c', usernames: { $nin: [ user.username ]} }) + room = RocketChat.models.Rooms.findOneByNameAndTypeNotContainigUsername(channel, 'c', user.username) if not room? return diff --git a/packages/rocketchat-statistics/package.js b/packages/rocketchat-statistics/package.js index 4c5198b7a2e5..61845b602086 100644 --- a/packages/rocketchat-statistics/package.js +++ b/packages/rocketchat-statistics/package.js @@ -24,7 +24,8 @@ Package.onUse(function(api) { // Statistics api.addFiles('lib/rocketchat.coffee', [ 'client', 'server' ]); api.addFiles([ - 'server/collections/Statistics.coffee', + 'server/models/Statistics.coffee', + 'server/models/MRStatistics.coffee', 'server/functions/get.coffee', 'server/functions/save.coffee', 'server/methods/getStatistics.coffee' diff --git a/packages/rocketchat-statistics/server/collections/MapReducedStatistics.coffee b/packages/rocketchat-statistics/server/collections/MapReducedStatistics.coffee deleted file mode 100644 index be489dba3708..000000000000 --- a/packages/rocketchat-statistics/server/collections/MapReducedStatistics.coffee +++ /dev/null @@ -1 +0,0 @@ -@MapReducedStatistics = new Meteor.Collection 'rocketchat_mr_statistics' diff --git a/packages/rocketchat-statistics/server/collections/Statistics.coffee b/packages/rocketchat-statistics/server/collections/Statistics.coffee deleted file mode 100644 index 3cf64d0319c5..000000000000 --- a/packages/rocketchat-statistics/server/collections/Statistics.coffee +++ /dev/null @@ -1 +0,0 @@ -@Statistics = new Meteor.Collection 'rocketchat_statistics' diff --git a/packages/rocketchat-statistics/server/functions/get.coffee b/packages/rocketchat-statistics/server/functions/get.coffee index e79c9c68118c..378e4b1943fd 100644 --- a/packages/rocketchat-statistics/server/functions/get.coffee +++ b/packages/rocketchat-statistics/server/functions/get.coffee @@ -1,8 +1,8 @@ RocketChat.statistics.get = -> statistics = {} - + # Version - statistics.uniqueId = Settings.findOne({ _id: "uniqueID" })?.value + statistics.uniqueId = RocketChat.settings.get("uniqueID") statistics.version = BuildInfo?.commit?.hash statistics.versionDate = BuildInfo?.commit?.date @@ -15,16 +15,16 @@ RocketChat.statistics.get = -> statistics.offlineUsers = statistics.totalUsers - statistics.onlineUsers - statistics.awayUsers # Room statistics - statistics.totalRooms = ChatRoom.find().count() - statistics.totalChannels = ChatRoom.find({ t: 'c' }).count() - statistics.totalPrivateGroups = ChatRoom.find({ t: 'p' }).count() - statistics.totalDirect = ChatRoom.find({ t: 'd' }).count() + statistics.totalRooms = RocketChat.models.Rooms.find().count() + statistics.totalChannels = RocketChat.models.Rooms.findByType('c').count() + statistics.totalPrivateGroups = RocketChat.models.Rooms.findByType('p').count() + statistics.totalDirect = RocketChat.models.Rooms.findByType('d').count() # Message statistics - statistics.totalMessages = ChatMessage.find().count() + statistics.totalMessages = RocketChat.models.Messages.find().count() m = -> - emit 1, + emit 1, sum: this.usernames.length or 0 min: this.usernames.length or 0 max: this.usernames.length or 0 @@ -44,34 +44,34 @@ RocketChat.statistics.get = -> a.max = Math.max a.max, b.max a.count += b.count return a - + f = (k, v) -> v.avg = v.sum / v.count return v - result = ChatRoom.mapReduce(m, r, { finalize: f, out: "rocketchat_mr_statistics" }) + result = RocketChat.models.Rooms.model.mapReduce(m, r, { finalize: f, out: "rocketchat_mr_statistics" }) - statistics.maxRoomUsers = 0 + statistics.maxRoomUsers = 0 statistics.avgChannelUsers = 0 statistics.avgPrivateGroupUsers = 0 - if MapReducedStatistics.findOne({ _id: 1 }) - statistics.maxRoomUsers = MapReducedStatistics.findOne({ _id: 1 }).value.max - else + if RocketChat.models.MRStatistics.findOneById(1) + statistics.maxRoomUsers = RocketChat.models.MRStatistics.findOneById(1).value.max + else console.log 'max room user statistic not found'.red - if MapReducedStatistics.findOne({ _id: 'c' }) - statistics.avgChannelUsers = MapReducedStatistics.findOne({ _id: 'c' }).value.avg + if RocketChat.models.MRStatistics.findOneById('c') + statistics.avgChannelUsers = RocketChat.models.MRStatistics.findOneById('c').value.avg else console.log 'channel user statistic not found'.red - if MapReducedStatistics.findOne({ _id: 'p' }) - statistics.avgPrivateGroupUsers = MapReducedStatistics.findOne({ _id: 'p' }).value.avg + if RocketChat.models.MRStatistics.findOneById('p') + statistics.avgPrivateGroupUsers = RocketChat.models.MRStatistics.findOneById('p').value.avg else console.log 'private group user statistic not found'.red - + os = Npm.require('os') - statistics.os = + statistics.os = type: os.type() platform: os.platform() arch: os.arch() @@ -82,4 +82,4 @@ RocketChat.statistics.get = -> freemem: os.freemem() cpus: os.cpus() - return statistics \ No newline at end of file + return statistics diff --git a/packages/rocketchat-statistics/server/functions/getAverage.coffee b/packages/rocketchat-statistics/server/functions/getAverage.coffee index 68098b50655e..27eccadd2a68 100644 --- a/packages/rocketchat-statistics/server/functions/getAverage.coffee +++ b/packages/rocketchat-statistics/server/functions/getAverage.coffee @@ -1,6 +1,6 @@ RocketChat.statistics.getAverage = -> statistics = {} - + m = -> d = this.createdAt this.count = 1 @@ -30,7 +30,7 @@ RocketChat.statistics.getAverage = -> a.os.loadavg[1] += b.os.loadavg[1] a.os.loadavg[2] += b.os.loadavg[2] return a - + f = (k, v) -> out = {} out.totalUsers = v.totalUsers / v.count @@ -53,6 +53,6 @@ RocketChat.statistics.getAverage = -> out.os.loadavg = [ (v.os.loadavg[0] / v.count), (v.os.loadavg[1] / v.count), (v.os.loadavg[2] / v.count) ] return out - result = Statistics.mapReduce(m, r, { finalize: f, out: "rocketchat_mr_statistics" }) - statistics = MapReducedStatistics.find().fetch() - return statistics \ No newline at end of file + result = RocketChat.models.Statistics.model.mapReduce(m, r, { finalize: f, out: "rocketchat_mr_statistics" }) + statistics = RocketChat.models.MRStatistics.find().fetch() + return statistics diff --git a/packages/rocketchat-statistics/server/functions/save.coffee b/packages/rocketchat-statistics/server/functions/save.coffee index ed19daf541e3..9752d42f43c8 100644 --- a/packages/rocketchat-statistics/server/functions/save.coffee +++ b/packages/rocketchat-statistics/server/functions/save.coffee @@ -1,6 +1,6 @@ RocketChat.statistics.save = -> statistics = RocketChat.statistics.get() statistics.createdAt = new Date - Statistics.insert statistics + RocketChat.models.Statistics.insert statistics return statistics diff --git a/packages/rocketchat-statistics/server/models/MRStatistics.coffee b/packages/rocketchat-statistics/server/models/MRStatistics.coffee new file mode 100644 index 000000000000..135982f71d8f --- /dev/null +++ b/packages/rocketchat-statistics/server/models/MRStatistics.coffee @@ -0,0 +1,11 @@ +RocketChat.models.MRStatistics = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'mr_statistics' + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options diff --git a/packages/rocketchat-statistics/server/models/Statistics.coffee b/packages/rocketchat-statistics/server/models/Statistics.coffee new file mode 100644 index 000000000000..79ae41e7869d --- /dev/null +++ b/packages/rocketchat-statistics/server/models/Statistics.coffee @@ -0,0 +1,11 @@ +RocketChat.models.Statistics = new class extends RocketChat.models._Base + constructor: -> + @_initModel 'statistics' + + + # FIND ONE + findOneById: (_id, options) -> + query = + _id: _id + + return @findOne query, options diff --git a/server/configuration/accounts_meld.coffee b/server/configuration/accounts_meld.coffee index 11c5206caf46..e03c09e36b31 100644 --- a/server/configuration/accounts_meld.coffee +++ b/server/configuration/accounts_meld.coffee @@ -19,19 +19,12 @@ Accounts.updateOrCreateUserFromExternalService = (serviceName, serviceData, opti if serviceData.email # Remove not verified users that have same email - notVerifiedUser = Meteor.users.remove({emails: {$elemMatch: {address: serviceData.email, verified: false}}}) + RocketChat.models.Users.removeByUnverifiedEmail serviceData.email # Try to get existent user with same email verified - user = Meteor.users.findOne({emails: {$elemMatch: {address: serviceData.email, verified: true}}}) + user = RocketChat.models.Users.findOneByVerifiedEmailAddress(serviceData.email, true) if user? - serviceIdKey = "services." + serviceName + ".id" - update = {} - update[serviceIdKey] = serviceData.id - Meteor.users.update({ - _id: user._id - }, { - $set: update - }) + RocketChat.models.Users.setServiceId user._id, serviceName, serviceData.id return orig_updateOrCreateUserFromExternalService.apply(this, arguments) diff --git a/server/lib/accounts.coffee b/server/lib/accounts.coffee index 17748e6c2df6..402204f2a91b 100644 --- a/server/lib/accounts.coffee +++ b/server/lib/accounts.coffee @@ -51,9 +51,9 @@ Accounts.insertUserDoc = _.wrap Accounts.insertUserDoc, (insertUserDoc) -> _id = insertUserDoc(options, user) # when inserting first user give them admin privileges otherwise make a regular user - firstUser = Meteor.users.findOne({},{sort:{createdAt:1}}) + firstUser = RocketChat.models.Users.findOne({},{sort:{createdAt:1}}) roleName = if firstUser?._id is _id then 'admin' else 'user' - + RocketChat.authz.addUsersToRoles(_id, roleName) RocketChat.callbacks.run 'afterCreateUser', options, user return _id @@ -76,7 +76,8 @@ Accounts.validateLoginAttempt (login) -> throw new Meteor.Error 'no-valid-email' return false - Meteor.users.update {_id: login.user._id}, {$set: {lastLogin: new Date}} + RocketChat.models.Users.updateLastLoginById login.user._id + Meteor.defer -> RocketChat.callbacks.run 'afterValidateLogin', login diff --git a/server/lib/collections.coffee b/server/lib/collections.coffee deleted file mode 100644 index cf46a682a082..000000000000 --- a/server/lib/collections.coffee +++ /dev/null @@ -1,5 +0,0 @@ -@ChatMessage = new Meteor.Collection 'rocketchat_message' -@ChatRoom = new Meteor.Collection 'rocketchat_room' -@ChatSubscription = new Meteor.Collection 'rocketchat_subscription' -@MapReducedStatistics = new Mongo.Collection 'rocketchat_mr_statistics' -@ChatReports = new Meteor.Collection 'rocketchat_reports' diff --git a/server/methods/addUserToRoom.coffee b/server/methods/addUserToRoom.coffee index 2a62255bcc91..5edcc19e39a0 100644 --- a/server/methods/addUserToRoom.coffee +++ b/server/methods/addUserToRoom.coffee @@ -3,7 +3,7 @@ Meteor.methods fromId = Meteor.userId() # console.log '[methods] addUserToRoom -> '.green, 'fromId:', fromId, 'data:', data - room = ChatRoom.findOne data.rid + room = RocketChat.models.Rooms.findOneById data.rid # if room.username isnt Meteor.user().username and room.t is 'c' if room.t is 'c' and room.u?.username isnt Meteor.user().username @@ -13,35 +13,19 @@ Meteor.methods if room.usernames.indexOf(data.username) isnt -1 return - now = new Date() - - update = - $addToSet: - usernames: data.username + newUser = RocketChat.models.Users.findOneByUsername username: data.username - newUser = Meteor.users.findOne username: data.username + RocketChat.models.Rooms.addUsernameById data.rid, data.username - ChatRoom.update data.rid, update + now = new Date() - ChatSubscription.insert - rid: data.rid + RocketChat.models.Subscriptions.createWithRoomAndUser room, newUser, ts: now - name: room.name - t: room.t open: true alert: true unread: 1 - u: - _id: newUser._id - username: data.username - ChatMessage.insert - rid: data.rid + RocketChat.models.Messages.createUserAddedWithRoomIdAndUser data.rid, newUser, ts: now - t: 'au' - msg: newUser.name - u: - _id: fromId - username: Meteor.user().username return true diff --git a/server/methods/archiveRoom.coffee b/server/methods/archiveRoom.coffee index 8fabd2efa3e4..abfcef70b12c 100644 --- a/server/methods/archiveRoom.coffee +++ b/server/methods/archiveRoom.coffee @@ -5,25 +5,18 @@ Meteor.methods console.log '[methods] archiveRoom -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - room = ChatRoom.findOne rid + room = RocketChat.models.Rooms.findOneById rid if room.u? and room.u._id is Meteor.userId() or RocketChat.authz.hasRole(Meteor.userId(), 'admin') update = $set: archived: true - ChatRoom.update rid, update + RocketChat.models.Rooms.archiveById rid for username in room.usernames - member = Meteor.users.findOne({ username: username },{ fields: { username: 1 }}) + member = RocketChat.models.Users.findOneByUsername(username, { fields: { username: 1 }}) if not member? continue - ChatSubscription.update - rid: rid - 'u._id': member._id - , - $set: - alert: false - open: false - archived: true + RocketChat.models.Subscriptions.archiveByRoomIdAndUserId rid, member._id diff --git a/server/methods/canAccessRoom.coffee b/server/methods/canAccessRoom.coffee index 49acd6381e87..2d5cd6ff3303 100644 --- a/server/methods/canAccessRoom.coffee +++ b/server/methods/canAccessRoom.coffee @@ -2,7 +2,7 @@ Meteor.methods canAccessRoom: (rid, userId) -> console.log '[methods] canAccessRoom -> '.green, 'userId:', userId, 'rid:', rid - user = Meteor.users.findOne userId, fields: username: 1 + user = RocketChat.models.Users.findOneById userId, fields: username: 1 unless user?.username throw new Meteor.Error 'not-logged-user', "[methods] canAccessRoom -> User doesn't have enough permissions" @@ -10,7 +10,7 @@ Meteor.methods unless rid throw new Meteor.Error 'invalid-room', '[methods] canAccessRoom -> Cannot access empty room' - room = ChatRoom.findOne rid, { fields: { usernames: 1, t: 1, name: 1 } } + room = RocketChat.models.Rooms.findOneById rid, { fields: { usernames: 1, t: 1, name: 1 } } if room if room.t is 'c' diff --git a/server/methods/channelsList.coffee b/server/methods/channelsList.coffee index 63e8154cb728..7aa42ff63518 100644 --- a/server/methods/channelsList.coffee +++ b/server/methods/channelsList.coffee @@ -1,3 +1,3 @@ Meteor.methods channelsList: -> - return { channels: ChatRoom.find({ t: 'c' }, { sort: { msgs:-1 } }).fetch() } + return { channels: RocketChat.models.Rooms.findByType('c', { sort: { msgs:-1 } }).fetch() } diff --git a/server/methods/createChannel.coffee b/server/methods/createChannel.coffee index c602b9492772..c3dff18c170b 100644 --- a/server/methods/createChannel.coffee +++ b/server/methods/createChannel.coffee @@ -17,53 +17,43 @@ Meteor.methods members.push user.username # avoid duplicate names - if ChatRoom.findOne({name:name}) + if RocketChat.models.Rooms.findOneByName name throw new Meteor.Error 'duplicate-name' # name = s.slugify name - room = - usernames: members - ts: now + RocketChat.callbacks.run 'beforeCreateChannel', user, t: 'c' name: name - msgs: 0 + ts: now + usernames: members u: - _id: Meteor.userId() + _id: user._id username: user.username - RocketChat.callbacks.run 'beforeCreateChannel', user, room - # create new room - rid = ChatRoom.insert room + room = RocketChat.models.Rooms.createWithTypeNameUserAndUsernames 'c', name, user, members, + ts: now + # set creator as channel moderator. permission limited to channel by scoping to rid - RocketChat.authz.addUsersToRoles(Meteor.userId(), 'moderator', rid) + RocketChat.authz.addUsersToRoles(Meteor.userId(), 'moderator', room._id) for username in members - member = Meteor.users.findOne({username: username}) + member = RocketChat.models.Users.findOneByUsername username if not member? continue - sub = - rid: rid - ts: now - name: name - t: 'c' - unread: 0 - u: - _id: member._id - username: username + extra = {} if username is user.username - sub.ls = now - sub.open = true + extra.ls = now + extra.open = true - ChatSubscription.insert sub + RocketChat.models.Subscriptions.createWithRoomAndUser room, member, extra Meteor.defer -> - RocketChat.callbacks.run 'afterCreateChannel', user, room return { - rid: rid + rid: room._id } diff --git a/server/methods/createDirectMessage.coffee b/server/methods/createDirectMessage.coffee index d2fe91504a57..cffe60ca2766 100644 --- a/server/methods/createDirectMessage.coffee +++ b/server/methods/createDirectMessage.coffee @@ -10,8 +10,7 @@ Meteor.methods if me.username is username return - to = Meteor.users.findOne - username: username + to = RocketChat.models.Users.findOneByUsername username if not to throw new Meteor.Error('invalid-user', "[methods] createDirectMessage -> Invalid target user") @@ -21,7 +20,7 @@ Meteor.methods now = new Date() # Make sure we have a room - ChatRoom.upsert + RocketChat.models.Rooms.upsert _id: rid , $set: @@ -32,9 +31,9 @@ Meteor.methods ts: now # Make user I have a subcription to this room - ChatSubscription.upsert + RocketChat.models.Subscriptions.upsert rid: rid - $and: [{'u._id': me._id}] + 'u._id': me._id , $set: ts: now @@ -50,9 +49,9 @@ Meteor.methods username: me.username # Make user the target user has a subcription to this room - ChatSubscription.upsert + RocketChat.models.Subscriptions.upsert rid: rid - $and: [{'u._id': to._id}] + 'u._id': to._id , $setOnInsert: name: me.username diff --git a/server/methods/createPrivateGroup.coffee b/server/methods/createPrivateGroup.coffee index 351031eebbef..81f20a0bd4d1 100644 --- a/server/methods/createPrivateGroup.coffee +++ b/server/methods/createPrivateGroup.coffee @@ -3,7 +3,7 @@ Meteor.methods if not Meteor.userId() throw new Meteor.Error 'invalid-user', "[methods] createPrivateGroup -> Invalid user" - unless RocketChat.authz.hasPermission(Meteor.userId(), 'create-p') + unless RocketChat.authz.hasPermission(Meteor.userId(), 'create-p') throw new Meteor.Error 'not-authorized', '[methods] createPrivateGroup -> Not authorized' console.log '[methods] createPrivateGroup -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments @@ -20,45 +20,30 @@ Meteor.methods name = s.slugify name # avoid duplicate names - if ChatRoom.findOne({name:name}) + if RocketChat.models.Rooms.findOneByName name throw new Meteor.Error 'duplicate-name' # create new room - rid = ChatRoom.insert - usernames: members + room = RocketChat.models.Rooms.createWithTypeNameUserAndUsernames 'p', name, me, members, ts: now - t: 'p' - u: - _id: me._id - username: me.username - name: name - msgs: 0 # set creator as group moderator. permission limited to group by scoping to rid - RocketChat.authz.addUsersToRoles(Meteor.userId(), 'moderator', rid) + RocketChat.authz.addUsersToRoles(Meteor.userId(), 'moderator', room._id) for username in members - member = Meteor.users.findOne({ username: username },{ fields: { username: 1 }}) + member = RocketChat.models.Users.findOneByUsername(username, { fields: { username: 1 }}) if not member? continue - subscription = - rid: rid - ts: now - name: name - t: 'p' - open: true - u: - _id: member._id - username: member.username + extra = {} if username is me.username - subscription.ls = now + extra.ls = now else - subscription.alert = true + extra.alert = true - ChatSubscription.insert subscription + RocketChat.models.Subscriptions.createWithRoomAndUser room, member, extra return { - rid: rid + rid: room._id } diff --git a/server/methods/deleteMessage.coffee b/server/methods/deleteMessage.coffee index 8a9288b437c7..fbf66bb76b25 100644 --- a/server/methods/deleteMessage.coffee +++ b/server/methods/deleteMessage.coffee @@ -3,7 +3,7 @@ Meteor.methods if not Meteor.userId() throw new Meteor.Error('invalid-user', "[methods] deleteMessage -> Invalid user") - originalMessage = ChatMessage.findOne message._id, {fields: {u: 1, rid: 1}} + originalMessage = RocketChat.models.Messages.findOneById message._id, {fields: {u: 1, rid: 1}} if not originalMessage? throw new Meteor.Error 'message-deleting-not-allowed', "[methods] deleteMessage -> Message with id [#{message._id} dos not exists]" @@ -20,31 +20,17 @@ Meteor.methods keepHistory = RocketChat.settings.get 'Message_KeepHistory' showDeletedStatus = RocketChat.settings.get 'Message_ShowDeletedStatus' - deleteQuery = - _id: originalMessage._id - if keepHistory if showDeletedStatus - history = ChatMessage.findOne originalMessage._id - history._hidden = true - history.parent = history._id - history.ets = new Date() - delete history._id - ChatMessage.insert history + RocketChat.models.Messages.cloneAndSaveAsHistoryById originalMessage._id else - ChatMessage.update deleteQuery, - $set: - _hidden: true + RocketChat.models.Messages.setHiddenById originalMessage._id, true else if not showDeletedStatus - ChatMessage.remove deleteQuery + RocketChat.models.Messages.removeById originalMessage._id if showDeletedStatus - ChatMessage.update deleteQuery, - $set: - msg: '' - t: 'rm' - ets: new Date() + RocketChat.models.Messages.setAsDeletedById originalMessage._id else RocketChat.Notifications.notifyRoom originalMessage.rid, 'deleteMessage', { _id: originalMessage._id } diff --git a/server/methods/deleteUser.coffee b/server/methods/deleteUser.coffee index 73fe0d475d73..b388826833bf 100644 --- a/server/methods/deleteUser.coffee +++ b/server/methods/deleteUser.coffee @@ -2,33 +2,31 @@ Meteor.methods deleteUser: (userId) -> if not Meteor.userId() throw new Meteor.Error('invalid-user', "[methods] deleteUser -> Invalid user") - - user = Meteor.users.findOne Meteor.userId() + + user = RocketChat.models.Users.findOneById Meteor.userId() + unless RocketChat.authz.hasPermission(Meteor.userId(), 'delete-user') is true throw new Meteor.Error 'not-authorized', '[methods] deleteUser -> Not authorized' - user = Meteor.users.findOne userId + user = RocketChat.models.Users.findOneById userId unless user? throw new Meteor.Error 'not-found', '[methods] deleteUser -> User not found' - ChatMessage.remove { "u._id": userId } # Remove user messages + RocketChat.models.Messages.removeByUserId userId # Remove user messages - ChatSubscription.find({ "u._id": userId }).forEach (subscription) -> - room = ChatRoom.findOne subscription.rid + RocketChat.models.Subscriptions.findByUserId(userId).forEach (subscription) -> + room = RocketChat.models.Rooms.findOneById subscription.rid if room.t isnt 'c' and room.usernames.length is 1 - ChatRoom.remove subscription.rid # Remove non-channel rooms with only 1 user (the one being deleted) - - - + RocketChat.models.Rooms.removeById subscription.rid # Remove non-channel rooms with only 1 user (the one being deleted) - ChatSubscription.remove { "u._id": userId } # Remove user subscriptions + RocketChat.models.Subscriptions.removeByUserId userId # Remove user subscriptions - rooms = ChatRoom.find({ "u._id": userId }).fetch() + rooms = RocketChat.models.Rooms.findByUserId(userId).fetch() - ChatRoom.remove { t: 'd', usernames: user.username } # Remove direct rooms with the user - ChatRoom.update {}, { $pull: { usernames: user.username } }, { multi: true } # Remove user from all other rooms - Meteor.users.remove { _id: userId } # Remove user from users database + RocketChat.models.Rooms.removeByTypeContainingUsername 'd', user.username # Remove direct rooms with the user + RocketChat.models.Rooms.removeUsernameFromAll user.username # Remove user from all other rooms + RocketChat.models.Users.removeById userId # Remove user from users database - return true \ No newline at end of file + return true diff --git a/server/methods/eraseRoom.coffee b/server/methods/eraseRoom.coffee index 07bb065c3d16..a8c6f8248b7a 100644 --- a/server/methods/eraseRoom.coffee +++ b/server/methods/eraseRoom.coffee @@ -2,20 +2,16 @@ Meteor.methods eraseRoom: (rid) -> fromId = Meteor.userId() - roomType = ChatRoom.findOne(rid)?.t + roomType = RocketChat.models.Rooms.findOneById(rid)?.t if RocketChat.authz.hasPermission( fromId, "delete-#{roomType}", rid ) # console.log '[methods] eraseRoom -> '.green, 'fromId:', fromId, 'rid:', rid # ChatRoom.update({ _id: rid}, {'$pull': { userWatching: Meteor.userId(), userIn: Meteor.userId() }}) - userUnset = {'$unset': {}} - userUnset.$unset['readMessages.' + rid] = '' - Meteor.users.update({_id: Meteor.userId()}, userUnset) - - ChatMessage.remove({rid: rid}) - ChatSubscription.remove({rid: rid}) - ChatRoom.remove(rid) + RocketChat.models.Messages.removeByRoomId rid + RocketChat.models.Subscriptions.removeByRoomId rid + RocketChat.models.Rooms.removeById rid # @TODO remove das mensagens lidas do usuário - else + else throw new Meteor.Error 'unauthorized' diff --git a/server/methods/getUsernameSuggestion.coffee b/server/methods/getUsernameSuggestion.coffee index 7b716a95edaa..72133e431a35 100644 --- a/server/methods/getUsernameSuggestion.coffee +++ b/server/methods/getUsernameSuggestion.coffee @@ -9,7 +9,7 @@ usernameIsAvaliable = (username) -> if username is 'all' return false - return not Meteor.users.findOne({username: {$regex : new RegExp(username, "i") }}) + return not RocketChat.models.Users.findOneByUsername({$regex : new RegExp(username, "i") }) @generateSuggestion = (user) -> usernames = [] diff --git a/server/methods/hideRoom.coffee b/server/methods/hideRoom.coffee index af7e72f7ae54..3537394aef40 100644 --- a/server/methods/hideRoom.coffee +++ b/server/methods/hideRoom.coffee @@ -5,10 +5,4 @@ Meteor.methods console.log '[methods] hideRoom -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - ChatSubscription.update - rid: rid - 'u._id': Meteor.userId() - , - $set: - alert: false - open: false + RocketChat.models.Subscriptions.hideByRoomIdAndUserId rid, Meteor.userId() diff --git a/server/methods/joinRoom.coffee b/server/methods/joinRoom.coffee index b5b7ea0db33a..a13795074648 100644 --- a/server/methods/joinRoom.coffee +++ b/server/methods/joinRoom.coffee @@ -1,7 +1,7 @@ Meteor.methods joinRoom: (rid) -> - room = ChatRoom.findOne rid + room = RocketChat.models.Rooms.findOneById rid if room.t isnt 'c' throw new Meteor.Error 403, '[methods] joinRoom -> Not allowed' @@ -12,39 +12,22 @@ Meteor.methods now = new Date() - user = Meteor.users.findOne Meteor.userId() + user = RocketChat.models.Users.findOneById Meteor.userId() RocketChat.callbacks.run 'beforeJoinRoom', user, room - update = - $addToSet: - usernames: user.username + RocketChat.models.Rooms.addUsernameById rid, user.username - ChatRoom.update rid, update - - ChatSubscription.insert - rid: rid + RocketChat.models.Subscriptions.createWithRoomAndUser room, user, ts: now - name: room.name - t: room.t open: true alert: true unread: 1 - u: - _id: user._id - username: user.username - ChatMessage.insert - rid: rid + RocketChat.models.Messages.createUserJoinWithRoomIdAndUser rid, user, ts: now - t: 'uj' - msg: user.name - u: - _id: user._id - username: user.username Meteor.defer -> - RocketChat.callbacks.run 'afterJoinRoom', user, room return true diff --git a/server/methods/leaveRoom.coffee b/server/methods/leaveRoom.coffee index b0f6b5d81195..6e15ab311761 100644 --- a/server/methods/leaveRoom.coffee +++ b/server/methods/leaveRoom.coffee @@ -6,48 +6,27 @@ Meteor.methods unless Meteor.userId()? throw new Meteor.Error 300, 'Usuário não logado' - room = ChatRoom.findOne rid + room = RocketChat.models.Rooms.findOneById rid user = Meteor.user() RocketChat.callbacks.run 'beforeLeaveRoom', user, room - update = - $pull: - usernames: user.username - - ChatSubscription.update { rid: rid }, - $set: - name: room.name - , - multi: true + RocketChat.models.Rooms.removeUsernameById rid, user.username if room.t isnt 'c' and room.usernames.indexOf(user.username) isnt -1 removedUser = user - ChatMessage.insert - rid: rid - ts: (new Date) - t: 'ul' - msg: removedUser.name - u: - _id: removedUser._id - username: removedUser.username + RocketChat.models.Messages.createUserJoinWithRoomIdAndUser rid, removedUser - if room.u? and room.u._id is Meteor.userId() + if room.u?._id is Meteor.userId() newOwner = _.without(room.usernames, user.username)[0] if newOwner? - newOwner = Meteor.users.findOne username: newOwner + newOwner = RocketChat.models.Users.findOneByUsername newOwner if newOwner? - if not update.$set? - update.$set = {} - - update.$set['u._id'] = newOwner._id - update.$set['u.username'] = newOwner.username - - ChatSubscription.remove { rid: rid, 'u._id': Meteor.userId() } + RocketChat.models.Rooms.setUserById rid, newOwner - ChatRoom.update rid, update + RocketChat.models.Subscriptions.removeByRoomIdAndUserId rid, Meteor.userId() Meteor.defer -> diff --git a/server/methods/loadHistory.coffee b/server/methods/loadHistory.coffee index 4d15af60a7ee..6e9afe038a4c 100644 --- a/server/methods/loadHistory.coffee +++ b/server/methods/loadHistory.coffee @@ -20,16 +20,14 @@ Meteor.methods if not RocketChat.settings.get 'Message_ShowEditedStatus' options.fields = { ets: 0 } - messages = ChatMessage.find(query, options).fetch() + messages = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestamp(rid, end, options).fetch() unreadNotLoaded = 0 if ls? - fistMessage = messages[messages.length - 1] - if fistMessage?.ts > ls - query.ts.$lt = fistMessage.ts - query.ts.$gt = ls + firstMessage = messages[messages.length - 1] + if firstMessage?.ts > ls delete options.limit - unreadNotLoaded = ChatMessage.find(query, options).count() + unreadNotLoaded = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestamps(rid, ls, firstMessage.ts).count() return { messages: messages diff --git a/server/methods/loadMissedMessages.coffee b/server/methods/loadMissedMessages.coffee index 63a1df62f9ad..7978c0b62245 100644 --- a/server/methods/loadMissedMessages.coffee +++ b/server/methods/loadMissedMessages.coffee @@ -6,12 +6,6 @@ Meteor.methods unless Meteor.call 'canAccessRoom', rid, fromId return false - query = - _hidden: { $ne: true } - rid: rid - ts: - $gt: start - options = sort: ts: -1 @@ -19,4 +13,4 @@ Meteor.methods if not RocketChat.settings.get 'Message_ShowEditedStatus' options.fields = { ets: 0 } - return ChatMessage.find(query, options).fetch() + return RocketChat.models.Messages.findVisibleByRoomIdAfterTimestamp(rid, start, options).fetch() diff --git a/server/methods/messageSearch.coffee b/server/methods/messageSearch.coffee index 14034fb29c7b..0f1a714d3925 100644 --- a/server/methods/messageSearch.coffee +++ b/server/methods/messageSearch.coffee @@ -61,7 +61,7 @@ Meteor.methods query.rid = rid try if Meteor.call('canAccessRoom', rid, this.userId) isnt false - result.messages = ChatMessage.find(query, options).fetch() + result.messages = RocketChat.models.Messages.find(query, options).fetch() # ### diff --git a/server/methods/openRoom.coffee b/server/methods/openRoom.coffee index d3ab6783b764..9dcb5d818d2b 100644 --- a/server/methods/openRoom.coffee +++ b/server/methods/openRoom.coffee @@ -5,9 +5,4 @@ Meteor.methods console.log '[methods] openRoom -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - ChatSubscription.update - rid: rid - 'u._id': Meteor.userId() - , - $set: - open: true + RocketChat.models.Subscriptions.openByRoomIdAndUserId rid, Meteor.userId() diff --git a/server/methods/pinMessage.coffee b/server/methods/pinMessage.coffee index e4076e1149e3..727e230fc096 100644 --- a/server/methods/pinMessage.coffee +++ b/server/methods/pinMessage.coffee @@ -10,26 +10,14 @@ Meteor.methods # If we keep history of edits, insert a new message to store history information if RocketChat.settings.get 'Message_KeepHistory' - history = ChatMessage.findOne message._id - history._hidden = true - history.parent = history._id - history.pts = new Date() - delete history._id - ChatMessage.insert history - - message.pts = new Date() + RocketChat.models.Messages.cloneAndSaveAsHistoryById message._id + message.pinned = true message = RocketChat.callbacks.run 'beforeSaveMessage', message - ChatMessage.update - _id: message._id - 'u._id': Meteor.userId() - , - $set: - pinned: message.pinned - pts : message.pts + RocketChat.models.Messages.setPinnedByIdAndUserId message._id, Meteor.userId(), message.pinned # Meteor.defer -> - # RocketChat.callbacks.run 'afterSaveMessage', ChatMessage.findOne(message.id) + # RocketChat.callbacks.run 'afterSaveMessage', RocketChat.models.Messages.findOneById(message.id) diff --git a/server/methods/readMessages.coffee b/server/methods/readMessages.coffee index 33c1dfb6dc6d..35dc63a998dc 100644 --- a/server/methods/readMessages.coffee +++ b/server/methods/readMessages.coffee @@ -5,12 +5,4 @@ Meteor.methods console.log '[methods] readMessages -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - ChatSubscription.update - rid: rid - 'u._id': Meteor.userId() - , - $set: - open: true - alert: false - unread: 0 - ls: (new Date()) + RocketChat.models.Subscriptions.setAsReadByRoomIdAndUserId rid, Meteor.userId() diff --git a/server/methods/registerUser.coffee b/server/methods/registerUser.coffee index e7596a3a04be..ec9baf84f496 100644 --- a/server/methods/registerUser.coffee +++ b/server/methods/registerUser.coffee @@ -6,9 +6,7 @@ Meteor.methods userId = Accounts.createUser userData - Meteor.users.update userId, - $set: - name: formData.name + RocketChat.models.Users.setName userId, formData.name if userData.email Accounts.sendVerificationEmail(userId, userData.email); diff --git a/server/methods/removeRoom.coffee b/server/methods/removeRoom.coffee deleted file mode 100644 index 1579bae2b7bf..000000000000 --- a/server/methods/removeRoom.coffee +++ /dev/null @@ -1,10 +0,0 @@ -Meteor.methods - removeRoom: (rid) -> - fromId = Meteor.userId() - # console.log '[methods] removeRoom -> '.green, 'fromId:', fromId, 'rid:', rid - - ChatRoom.update({ _id: rid}, {'$pull': { userWatching: Meteor.userId(), userIn: Meteor.userId() }}) - - # ChatMessage.remove({rid: rid}) - # ChatRoom.remove(rid) - # @TODO remove das mensagens lidas do usuário diff --git a/server/methods/removeUserFromRoom.coffee b/server/methods/removeUserFromRoom.coffee index 5b31fc70e803..d600b6d991ce 100644 --- a/server/methods/removeUserFromRoom.coffee +++ b/server/methods/removeUserFromRoom.coffee @@ -3,20 +3,16 @@ Meteor.methods fromId = Meteor.userId() # console.log '[methods] removeUserFromRoom -> '.green, 'fromId:', fromId, 'data:', data - room = ChatRoom.findOne data.rid + room = RocketChat.models.Rooms.findOneById data.rid if room.u?._id isnt Meteor.userId() and room.t is 'c' throw new Meteor.Error 403, 'Not allowed' - update = - $pull: - usernames: data.username + removedUser = RocketChat.models.Users.findOneByUsername data.username - removedUser = Meteor.users.findOne username: data.username + RocketChat.models.Rooms.removeUsernameById data.rid, data.username - ChatRoom.update data.rid, update - - ChatSubscription.remove { 'u._id': data.username, rid: data.rid } + RocketChat.models.Subscriptions.removeByRoomIdAndUserId data.rid, data.username switch room.t when 'c' @@ -24,13 +20,6 @@ Meteor.methods when 'p' RocketChat.authz.removeUsersFromRole(removedUser._id; 'group-moderator', data.rid) - ChatMessage.insert - rid: data.rid - ts: (new Date) - t: 'ru' - msg: removedUser.name - u: - _id: Meteor.userId() - username: Meteor.user().username + RocketChat.models.Messages.createUserRemovedWithRoomIdAndUser data.rid, removedUser return true diff --git a/server/methods/reportMessage.coffee b/server/methods/reportMessage.coffee index 00140ec678e2..193ee7ebaf33 100644 --- a/server/methods/reportMessage.coffee +++ b/server/methods/reportMessage.coffee @@ -6,8 +6,4 @@ Meteor.methods if not description? or description.trim() is '' throw new Meteor.Error 'invalid-description', "[methods] reportMessage -> Invalid description" - ChatReports.insert - message: message - description: description - ts: new Date() - userId: Meteor.userId() + RocketChat.models.Reports.createWithMessageDescriptionAndUserId message, description, Meteor.userId() diff --git a/server/methods/resetAvatar.coffee b/server/methods/resetAvatar.coffee index 2b49fdbf3db0..c3e31abe5082 100644 --- a/server/methods/resetAvatar.coffee +++ b/server/methods/resetAvatar.coffee @@ -9,7 +9,7 @@ Meteor.methods RocketChatFileAvatarInstance.deleteFile "#{user.username}.jpg" - Meteor.users.update user._id, {$unset: {avatarOrigin: 1}} + RocketChat.models.Users.unsetAvatarOrigin user._id RocketChat.Notifications.notifyAll 'updateAvatar', {username: user.username} return diff --git a/server/methods/saveRoomName.coffee b/server/methods/saveRoomName.coffee index 23de97d60d5f..7dba0b2d710a 100644 --- a/server/methods/saveRoomName.coffee +++ b/server/methods/saveRoomName.coffee @@ -3,13 +3,13 @@ Meteor.methods if not Meteor.userId() throw new Meteor.Error('invalid-user', "[methods] sendMessage -> Invalid user") - room = ChatRoom.findOne rid + room = RocketChat.models.Rooms.findOneById rid if room.t not in ['c', 'p'] throw new Meteor.Error 403, 'Not allowed' unless RocketChat.authz.hasPermission(Meteor.userId(), 'edit-room', rid) - #if room.u._id isnt Meteor.userId() and not hasPermission + #if room.u._id isnt Meteor.userId() and not hasPermission throw new Meteor.Error 403, 'Not allowed' if not /^[0-9a-z-_]+$/.test name @@ -21,29 +21,13 @@ Meteor.methods return # avoid duplicate names - if ChatRoom.findOne({name:name}) + if RocketChat.models.Rooms.findOneByName name throw new Meteor.Error 'duplicate-name' - ChatRoom.update rid, - $set: - name: name - - ChatSubscription.update - rid: rid - , - $set: - name: name - alert: true - , - multi: true - - ChatMessage.insert - rid: rid - ts: (new Date) - t: 'r' - msg: name - u: - _id: Meteor.userId() - username: Meteor.user().username + RocketChat.models.Rooms.setNameById rid, name + + RocketChat.models.Subscriptions.updateNameByRoomId rid, name + + RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser rid, name, Meteor.user() return name diff --git a/server/methods/saveUserPreferences.coffee b/server/methods/saveUserPreferences.coffee index bd04edc631a2..4a7e414a0b2c 100644 --- a/server/methods/saveUserPreferences.coffee +++ b/server/methods/saveUserPreferences.coffee @@ -23,6 +23,6 @@ Meteor.methods if settings.autoImageLoad? preferences.autoImageLoad = if settings.autoImageLoad is "1" then true else false - Meteor.users.update Meteor.userId(), { $set: { "settings.preferences": preferences } } + RocketChat.models.Users.setPreferences Meteor.userId(), preferences return true diff --git a/server/methods/saveUserProfile.coffee b/server/methods/saveUserProfile.coffee index 4129201e9797..40131de389ee 100644 --- a/server/methods/saveUserProfile.coffee +++ b/server/methods/saveUserProfile.coffee @@ -2,7 +2,7 @@ Meteor.methods saveUserProfile: (settings) -> if Meteor.userId() if settings.language? - Meteor.users.update Meteor.userId(), { $set: { language: settings.language } } + RocketChat.models.Users.setLanguage Meteor.userId(), settings.language if settings.password? Accounts.setPassword Meteor.userId(), settings.password, { logout: false } @@ -12,6 +12,6 @@ Meteor.methods profile = {} - Meteor.users.update Meteor.userId(), { $set: { "settings.profile": profile } } + RocketChat.models.Users.setProfile Meteor.userId(), profile return true diff --git a/server/methods/sendConfirmationEmail.coffee b/server/methods/sendConfirmationEmail.coffee index 1b3f4977852e..40c1819d8d1f 100644 --- a/server/methods/sendConfirmationEmail.coffee +++ b/server/methods/sendConfirmationEmail.coffee @@ -1,6 +1,6 @@ Meteor.methods sendConfirmationEmail: (email) -> - user = Meteor.users.findOne {'emails.address': email} + user = RocketChat.models.Users.findOneByEmailAddress email if user? Accounts.sendVerificationEmail(user._id, email) diff --git a/server/methods/sendForgotPasswordEmail.coffee b/server/methods/sendForgotPasswordEmail.coffee index 2d0ef4f330d9..34dbf32eafe1 100644 --- a/server/methods/sendForgotPasswordEmail.coffee +++ b/server/methods/sendForgotPasswordEmail.coffee @@ -1,6 +1,6 @@ Meteor.methods sendForgotPasswordEmail: (email) -> - user = Meteor.users.findOne {'emails.address': email} + user = RocketChat.models.Users.findOneByEmailAddress email if user? Accounts.sendResetPasswordEmail(user._id, email) diff --git a/server/methods/sendMessage.coffee b/server/methods/sendMessage.coffee index 85d9f878889a..2b5f84c89a93 100644 --- a/server/methods/sendMessage.coffee +++ b/server/methods/sendMessage.coffee @@ -8,7 +8,7 @@ Meteor.methods console.log '[methods] sendMessage -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - user = Meteor.users.findOne Meteor.userId(), fields: username: 1 + user = RocketChat.models.Users.findOneById Meteor.userId(), fields: username: 1 room = Meteor.call 'canAccessRoom', message.rid, user._id diff --git a/server/methods/setAvatarFromService.coffee b/server/methods/setAvatarFromService.coffee index 475c005a5983..90df44e2ad2b 100644 --- a/server/methods/setAvatarFromService.coffee +++ b/server/methods/setAvatarFromService.coffee @@ -8,7 +8,7 @@ Meteor.methods user = Meteor.user() if service is 'initials' - Meteor.users.update {_id: user._id}, {$set: {avatarOrigin: service}} + RocketChat.models.Users.setAvatarOrigin user._id, service return {image, contentType} = RocketChatFile.dataURIParse dataURI @@ -17,7 +17,7 @@ Meteor.methods ws = RocketChatFileAvatarInstance.createWriteStream "#{user.username}.jpg", contentType ws.on 'end', Meteor.bindEnvironment -> Meteor.setTimeout -> - Meteor.users.update {_id: user._id}, {$set: {avatarOrigin: service}} + RocketChat.models.Users.setAvatarOrigin user._id, service RocketChat.Notifications.notifyAll 'updateAvatar', {username: user.username} , 500 diff --git a/server/methods/setUserActiveStatus.coffee b/server/methods/setUserActiveStatus.coffee index f93b9025887c..f7084ae499fc 100644 --- a/server/methods/setUserActiveStatus.coffee +++ b/server/methods/setUserActiveStatus.coffee @@ -6,9 +6,9 @@ Meteor.methods unless RocketChat.authz.hasPermission( Meteor.userId(), 'edit-other-user-active-status') is true throw new Meteor.Error 'not-authorized', '[methods] setUserActiveStatus -> Not authorized' - Meteor.users.update userId, { $set: { active: active } } + RocketChat.models.Users.setUserActive userId, active if active is false - Meteor.users.update userId, { $set: { "services.resume.loginTokens" : [] } } + RocketChat.models.Users.unsetLoginTokens userId - return true \ No newline at end of file + return true diff --git a/server/methods/toogleFavorite.coffee b/server/methods/toogleFavorite.coffee index f20b04d1e4c7..a8c4cf5fa994 100644 --- a/server/methods/toogleFavorite.coffee +++ b/server/methods/toogleFavorite.coffee @@ -5,9 +5,4 @@ Meteor.methods console.log '[methods] toogleFavorite -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - ChatSubscription.update - rid: rid - 'u._id': Meteor.userId() - , - $set: - f: f + RocketChat.models.Subscriptions.setFavoriteByRoomIdAndUserId rid, Meteor.userId() diff --git a/server/methods/unarchiveRoom.coffee b/server/methods/unarchiveRoom.coffee index 0ffd74202fe0..eed9cbfdc2d0 100644 --- a/server/methods/unarchiveRoom.coffee +++ b/server/methods/unarchiveRoom.coffee @@ -5,25 +5,14 @@ Meteor.methods console.log '[methods] unArchiveRoom -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments - room = ChatRoom.findOne rid + room = RocketChat.models.Rooms.findOneById rid if room.u? and room.u._id is Meteor.userId() or RocketChat.authz.hasRole(Meteor.userId(), 'admin') - update = - $set: - archived: false - - ChatRoom.update rid, update + RocketChat.models.Rooms.unarchiveById rid for username in room.usernames - member = Meteor.users.findOne({ username: username },{ fields: { username: 1 }}) + member = RocketChat.models.Users.findOneByUsername(username, { fields: { username: 1 }}) if not member? continue - ChatSubscription.update - rid: rid - 'u._id': member._id - , - $set: - alert: false - open: false - archived: false + RocketChat.models.Subscriptions.unarchiveByRoomIdAndUserId rid, member._id diff --git a/server/methods/unpinMessage.coffee b/server/methods/unpinMessage.coffee index 4bce5a9bcd7a..5381b5b796a3 100644 --- a/server/methods/unpinMessage.coffee +++ b/server/methods/unpinMessage.coffee @@ -10,26 +10,14 @@ Meteor.methods # If we keep history of edits, insert a new message to store history information if RocketChat.settings.get 'Message_KeepHistory' - history = ChatMessage.findOne message._id - history._hidden = true - history.parent = history._id - history.pts = new Date() - delete history._id - ChatMessage.insert history - - message.pts = new Date() + RocketChat.models.Messages.cloneAndSaveAsHistoryById message._id + message.pinned = false message = RocketChat.callbacks.run 'beforeSaveMessage', message - ChatMessage.update - _id: message._id - 'u._id': Meteor.userId() - , - $set: - pinned: message.pinned - pts : message.pts + RocketChat.models.Messages.setPinnedByIdAndUserId message._id, Meteor.userId(), message.pinned # Meteor.defer -> - # RocketChat.callbacks.run 'afterSaveMessage', ChatMessage.findOne(message.id) + # RocketChat.callbacks.run 'afterSaveMessage', RocketChat.models.Messages.findOneById(message.id) diff --git a/server/methods/updateMessage.coffee b/server/methods/updateMessage.coffee index 84fa9ffa0641..b7507dc91238 100644 --- a/server/methods/updateMessage.coffee +++ b/server/methods/updateMessage.coffee @@ -3,7 +3,7 @@ Meteor.methods if not Meteor.userId() throw new Meteor.Error('invalid-user', "[methods] updateMessage -> Invalid user") - originalMessage = ChatMessage.findOne message._id + originalMessage = RocketChat.models.Messages.findOneById message._id hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'edit-message', message.rid) editAllowed = RocketChat.settings.get 'Message_AllowEditing' @@ -23,11 +23,7 @@ Meteor.methods # If we keep history of edits, insert a new message to store history information if RocketChat.settings.get 'Message_KeepHistory' - originalMessage._hidden = true - originalMessage.parent = originalMessage._id - originalMessage.ets = new Date() - delete originalMessage._id - ChatMessage.insert originalMessage + RocketChat.models.Messages.cloneAndSaveAsHistoryById originalMessage._id message.ets = new Date() @@ -39,11 +35,11 @@ Meteor.methods tempid = message._id delete message._id - ChatMessage.update + RocketChat.models.Messages.update _id: tempid , $set: message # Meteor.defer -> - # RocketChat.callbacks.run 'afterSaveMessage', ChatMessage.findOne(message.id) + # RocketChat.callbacks.run 'afterSaveMessage', RocketChat.models.Messages.findOneById(message.id) diff --git a/server/methods/updateUserUtcOffset.coffee b/server/methods/updateUserUtcOffset.coffee index f5b800c257ed..a116647e1c23 100644 --- a/server/methods/updateUserUtcOffset.coffee +++ b/server/methods/updateUserUtcOffset.coffee @@ -5,4 +5,4 @@ Meteor.methods @unblock() - Meteor.users.update({_id: @userId, utcOffset: {$ne: utcOffset}}, {$set: {utcOffset: utcOffset}}) \ No newline at end of file + RocketChat.models.Users.setUtcOffset @userId, utcOffset diff --git a/server/publications/activeUsers.coffee b/server/publications/activeUsers.coffee index 8848f2b01905..ba420634b094 100644 --- a/server/publications/activeUsers.coffee +++ b/server/publications/activeUsers.coffee @@ -4,12 +4,7 @@ Meteor.publish 'activeUsers', -> console.log '[publish] activeUsers'.green - Meteor.users.find - username: - $exists: 1 - status: - $in: ['online', 'away', 'busy'] - , + RocketChat.models.Users.findUsersNotOffline fields: username: 1 status: 1 diff --git a/server/publications/adminRooms.coffee b/server/publications/adminRooms.coffee index f05252ee5823..bceec2d8c51a 100644 --- a/server/publications/adminRooms.coffee +++ b/server/publications/adminRooms.coffee @@ -8,22 +8,7 @@ Meteor.publish 'adminRooms', (filter, types, limit) -> unless _.isArray types types = [] - query = {} - - filter = _.trim filter - if filter - if limit is 1 - query = { name: filter } - else - filterReg = new RegExp filter, "i" - query = { $or: [ { name: filterReg }, { t: 'd', usernames: filterReg } ] } - - if types.length - query['t'] = { $in: types } - - console.log '[publish] adminRooms'.green, filter, types, limit, query - - ChatRoom.find query, + options = fields: name: 1 t: 1 @@ -31,4 +16,18 @@ Meteor.publish 'adminRooms', (filter, types, limit) -> u: 1 usernames: 1 limit: limit - sort: { name: 1 } + sort: + name: 1 + + filter = _.trim filter + + console.log '[publish] adminRooms'.green, filter, types, limit + + if filter and types.length + return RocketChat.models.Rooms.findByNameContainingAndTypes filter, types, options + + if filter + return RocketChat.models.Rooms.findByNameContaining filter, options + + if types.length + return RocketChat.models.Rooms.findByTypes types, options diff --git a/server/publications/filteredUsers.coffee b/server/publications/filteredUsers.coffee new file mode 100644 index 000000000000..f530ca213f12 --- /dev/null +++ b/server/publications/filteredUsers.coffee @@ -0,0 +1,34 @@ +Meteor.publish 'filteredUsers', (name) -> + unless this.userId + return this.ready() + + console.log '[publish] filteredUsers'.green, name + + exp = new RegExp(name, 'i') + + options = + fields: + username: 1 + name: 1 + status: 1 + utcOffset: 1 + sort: + lastLogin: -1 + limit: 5 + + pub = this + + cursorHandle = RocketChat.models.Users.findUsersByNameOrUsername(exp, options).observeChanges + added: (_id, record) -> + pub.added('filtered-users', _id, record) + + changed: (_id, record) -> + pub.changed('filtered-users', _id, record) + + removed: (_id, record) -> + pub.removed('filtered-users', _id, record) + + @ready() + @onStop -> + cursorHandle.stop() + return diff --git a/server/publications/fullUserData.coffee b/server/publications/fullUserData.coffee index b3dc5ba854b7..36949ab9142d 100644 --- a/server/publications/fullUserData.coffee +++ b/server/publications/fullUserData.coffee @@ -2,14 +2,14 @@ Meteor.publish 'fullUserData', (filter, limit) -> unless @userId return @ready() - user = Meteor.users.findOne @userId + user = RocketChat.models.Users.findOneById @userId fields = name: 1 username: 1 status: 1 utcOffset: 1 - + if RocketChat.authz.hasPermission( @userId, 'view-full-other-user-info') is true fields = _.extend fields, emails: 1 @@ -28,18 +28,18 @@ Meteor.publish 'fullUserData', (filter, limit) -> if not filter and limit is 1 return @ready() + options = + fields: fields + limit: limit + sort: { username: 1 } + + console.log '[publish] fullUserData'.green, filter, limit + if filter if limit is 1 - query = { username: filter } + return RocketChat.models.Users.findByUsername filter, options else filterReg = new RegExp filter, "i" - query = { $or: [ { username: filterReg }, { name: filterReg }, { "emails.address": filterReg } ] } - else - query = {} - - console.log '[publish] fullUserData'.green, filter, limit + return RocketChat.models.Users.findByUsernameNameOrEmailAddress filterReg, options - Meteor.users.find query, - fields: fields - limit: limit - sort: { username: 1 } + return RocketChat.models.Users.find {}, options diff --git a/server/publications/messages.coffee b/server/publications/messages.coffee index e218ca8cb90a..d45f1817a51e 100644 --- a/server/publications/messages.coffee +++ b/server/publications/messages.coffee @@ -12,11 +12,7 @@ Meteor.publish 'messages', (rid, start) -> if not Meteor.call 'canAccessRoom', rid, this.userId return this.ready() - cursor = ChatMessage.find - rid: rid - _hidden: - $ne: true - , + cursor = RocketChat.models.Messages.findVisibleByRoomId rid, sort: ts: -1 limit: 50 @@ -28,10 +24,7 @@ Meteor.publish 'messages', (rid, start) -> changed: (_id, record) -> publication.changed('rocketchat_message', _id, record) - cursorDelete = ChatMessage.find - rid: rid - _hidden: true - , + cursorDelete = RocketChat.models.Messages.findInvisibleByRoomId rid, fields: _id: 1 diff --git a/server/publications/onlineUsers.coffee b/server/publications/onlineUsers.coffee deleted file mode 100644 index 863149acfe43..000000000000 --- a/server/publications/onlineUsers.coffee +++ /dev/null @@ -1,43 +0,0 @@ -Meteor.publish 'onlineUsers', (name) -> - unless this.userId - return this.ready() - - console.log '[publish] onlineUsers'.green, name - - exp = new RegExp(name, 'i') - - query = - username: - $exists: 1 - - $or: [ - {name: exp} - {username: exp} - ] - - options = - fields: - username: 1 - name: 1 - status: 1 - utcOffset: 1 - sort: - lastLogin: -1 - limit: 5 - - pub = this - - cursorHandle = Meteor.users.find(query, options).observeChanges - added: (_id, record) -> - pub.added('online-users', _id, record) - - changed: (_id, record) -> - pub.changed('online-users', _id, record) - - removed: (_id, record) -> - pub.removed('online-users', _id, record) - - @ready() - @onStop -> - cursorHandle.stop() - return diff --git a/server/publications/privateHistory.coffee b/server/publications/privateHistory.coffee index 822861c27c34..9f8eb31f8714 100644 --- a/server/publications/privateHistory.coffee +++ b/server/publications/privateHistory.coffee @@ -4,9 +4,7 @@ Meteor.publish 'privateHistory', -> console.log '[publish] privateHistory'.green - ChatRoom.find - usernames: Meteor.users.findOne(this.userId).username - , + RocketChat.models.Rooms.findByContainigUsername RocketChat.models.Users.findOneById(this.userId).username, fields: t: 1 name: 1 diff --git a/server/publications/room.coffee b/server/publications/room.coffee index d61e636ea739..3c02536d9abe 100644 --- a/server/publications/room.coffee +++ b/server/publications/room.coffee @@ -10,32 +10,26 @@ Meteor.publish 'room', (typeName) -> type = typeName.substr(0, 1) name = typeName.substr(1) - query = {} + options = + fields: + name: 1 + t: 1 + cl: 1 + u: 1 + usernames: 1 - if type in ['c', 'p'] - query = - t: type - name: name + switch type + when 'c' + return RocketChat.models.Rooms.findByTypeContainigUsername 'c', name, options - if type is 'p' - user = Meteor.users.findOne this.userId, fields: username: 1 - query.usernames = user.username + when 'p' + user = RocketChat.models.Users.findOneById this.userId, fields: username: 1 + return RocketChat.models.Rooms.findByTypeAndNameContainigUsername 'p', name, user.username, options - else if type is 'd' - user = Meteor.users.findOne this.userId, fields: username: 1 - query = - t: 'd' - usernames: - $all: [user.username, name] + when 'd' + user = RocketChat.models.Users.findOneById this.userId, fields: username: 1 + return RocketChat.models.Rooms.findByTypeContainigUsername 'd', user.username, options # Change to validate access manualy # if not Meteor.call 'canAccessRoom', rid, this.userId # return this.ready() - - ChatRoom.find query, - fields: - name: 1 - t: 1 - cl: 1 - u: 1 - usernames: 1 diff --git a/server/publications/roomSearch.coffee b/server/publications/roomSearch.coffee index b29a4873c78a..e5d9a2ae375a 100644 --- a/server/publications/roomSearch.coffee +++ b/server/publications/roomSearch.coffee @@ -14,7 +14,7 @@ Meteor.publish 'roomSearch', (selector, options, collName) -> delete selector.type if not searchType? or searchType is 'u' - subHandleUsers = Meteor.users.find(selector, { limit: 10, fields: { name: 1, username: 1, status: 1 } }).observeChanges + subHandleUsers = RocketChat.models.Users.find(selector, { limit: 10, fields: { name: 1, username: 1, status: 1 } }).observeChanges added: (id, fields) -> data = { type: 'u', uid: id, name: fields.name, username: fields.username, status: fields.status } self.added("autocompleteRecords", id, data) @@ -24,8 +24,7 @@ Meteor.publish 'roomSearch', (selector, options, collName) -> self.removed("autocompleteRecords", id) if not searchType? or searchType is 'r' - roomSelector = _.extend { t: { $in: ['c','p'] }, usernames: Meteor.users.findOne(this.userId).username }, selector - subHandleRooms = ChatRoom.find(roomSelector, { limit: 10, fields: { t: 1, name: 1 } }).observeChanges + subHandleRooms = RocketChat.models.Rooms.findByTypesAndNotUserIdContainingUsername(['c', 'p'], selector.uid?.$ne, RocketChat.models.Users.findOneById(this.userId).username, { limit: 10, fields: { t: 1, name: 1 } }).observeChanges added: (id, fields) -> data = { type: 'r', rid: id, name: fields.name, t: fields.t } self.added("autocompleteRecords", id, data) diff --git a/server/publications/subscription.coffee b/server/publications/subscription.coffee index fdf1faf19e3b..f188e99522e3 100644 --- a/server/publications/subscription.coffee +++ b/server/publications/subscription.coffee @@ -4,9 +4,7 @@ Meteor.publish 'subscription', -> console.log '[publish] subscription'.green - ChatSubscription.find - 'u._id': this.userId - , + RocketChat.models.Subscriptions.findByUserId this.userId, fields: t: 1 ts: 1 diff --git a/server/publications/userChannels.coffee b/server/publications/userChannels.coffee index 1f1f046d4724..dbacf03b444d 100644 --- a/server/publications/userChannels.coffee +++ b/server/publications/userChannels.coffee @@ -5,14 +5,12 @@ Meteor.publish 'userChannels', (userId) -> if RocketChat.authz.hasPermission( @userId, 'view-other-user-channels') isnt true return this.ready() - query = { "u._id": userId } - console.log '[publish] userChannels'.green, userId - ChatSubscription.find query, + RocketChat.models.Subscriptions.findByUserId userId, fields: rid: 1, name: 1, t: 1, u: 1 - sort: { t: 1, name: 1 } \ No newline at end of file + sort: { t: 1, name: 1 } diff --git a/server/publications/userData.coffee b/server/publications/userData.coffee index 303c60dada13..3d7811c9f40b 100644 --- a/server/publications/userData.coffee +++ b/server/publications/userData.coffee @@ -4,7 +4,7 @@ Meteor.publish 'userData', -> console.log '[publish] userData'.green - Meteor.users.find this.userId, + RocketChat.models.Users.find this.userId, fields: name: 1 username: 1 diff --git a/server/restapi/restapi.coffee b/server/restapi/restapi.coffee index 60a0c02e6a1e..90ba65e19b12 100644 --- a/server/restapi/restapi.coffee +++ b/server/restapi/restapi.coffee @@ -11,7 +11,7 @@ Api.addRoute 'version', authRequired: false, Api.addRoute 'publicRooms', authRequired: true, get: -> - rooms = ChatRoom.find({ t: 'c' }, { sort: { msgs:-1 } }).fetch() + rooms = RocketChat.models.Rooms.findByType('c', { sort: { msgs:-1 } }).fetch() status: 'success', rooms: rooms # join a room @@ -35,7 +35,7 @@ Api.addRoute 'rooms/:id/messages', authRequired: true, get: -> try if Meteor.call('canAccessRoom', @urlParams.id, this.userId) - msgs = ChatMessage.find({rid: @urlParams.id, _hidden: {$ne: true}}, {sort: {ts: -1}}, {limit: 50}).fetch() + msgs = RocketChat.models.Messages.findVisibleByRoomId(@urlParams.id, {sort: {ts: -1}, limit: 50}).fetch() status: 'success', messages: msgs else statusCode: 403 # forbidden diff --git a/server/startup/indexes.coffee b/server/startup/indexes.coffee deleted file mode 100644 index 28eca27eefa1..000000000000 --- a/server/startup/indexes.coffee +++ /dev/null @@ -1,17 +0,0 @@ -Meteor.startup -> - Meteor.defer -> - try ChatRoom._ensureIndex { 'name': 1 }, { unique: 1, sparse: 1 } catch e then console.log e - try ChatRoom._ensureIndex { 'u._id': 1 } catch e then console.log e - - try ChatSubscription._ensureIndex { 'rid': 1, 'u._id': 1 }, { unique: 1 } catch e then console.log e - try ChatSubscription._ensureIndex { 'u._id': 1, 'name': 1, 't': 1 }, { unique: 1 } catch e then console.log e - try ChatSubscription._ensureIndex { 'open': 1 } catch e then console.log e - try ChatSubscription._ensureIndex { 'alert': 1 } catch e then console.log e - try ChatSubscription._ensureIndex { 'unread': 1 } catch e then console.log e - try ChatSubscription._ensureIndex { 'ts': 1 } catch e then console.log e - - try ChatMessage._ensureIndex { 'rid': 1, 'ts': 1 } catch e then console.log e - try ChatMessage._ensureIndex { 'ets': 1 }, { sparse: 1 } catch e then console.log e - try ChatMessage._ensureIndex { 'rid': 1, 't': 1, 'u._id': 1 } catch e then console.log e - try ChatMessage._ensureIndex { 'expireAt': 1 }, { expireAfterSeconds: 0 } catch e then console.log e - try ChatMessage._ensureIndex { 'msg': 'text' } catch e then console.log e diff --git a/server/startup/initialData.coffee b/server/startup/initialData.coffee index c3f7736fb779..567fb3af3eca 100644 --- a/server/startup/initialData.coffee +++ b/server/startup/initialData.coffee @@ -1,37 +1,24 @@ Meteor.startup -> Meteor.defer -> - # Insert server unique id if it doesn't exist - if not Settings.findOne { _id: 'uniqueID' } - Settings.insert - _id: 'uniqueID' - value: Random.id() - if not ChatRoom.findOne('name': 'general')? - ChatRoom.insert - _id: 'GENERAL' + if not RocketChat.models.Rooms.findOneByName('general')? + RocketChat.models.Rooms.createWithIdTypeAndName 'GENERAL', 'c', 'general', default: true - usernames: [] - ts: new Date() - t: 'c' - name: 'general' - msgs: 0 - if process.env.ADMIN_EMAIL? and process.env.ADMIN_PASS? + if process.env.ADMIN_EMAIL? and process.env.ADMIN_PASS? re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i if re.test process.env.ADMIN_EMAIL if _.isEmpty(RocketChat.authz.getUsersInRole( 'admin' ).fetch()) - if not Meteor.users.findOne({ "emails.address": process.env.ADMIN_EMAIL }) + if not RocketChat.models.Users.findOneByEmailAddress process.env.ADMIN_EMAIL console.log 'Inserting admin user'.red console.log "email: #{process.env.ADMIN_EMAIL} | password: #{process.env.ADMIN_PASS}".red - id = Meteor.users.insert - createdAt: new Date + id = RocketChat.models.Users.create emails: [ address: process.env.ADMIN_EMAIL verified: true ], name: 'Admin' - avatarOrigin: 'none' Accounts.setPassword id, process.env.ADMIN_PASS RocketChat.authz.addUsersToRoles( id, 'admin') @@ -46,7 +33,7 @@ Meteor.startup -> # Set oldest user as admin, if none exists yet if _.isEmpty( RocketChat.authz.getUsersInRole( 'admin' ).fetch()) # get oldest user - oldestUser = Meteor.users.findOne({}, { fields: { username: 1 }, sort: {createdAt: 1}}) + oldestUser = RocketChat.models.Users.findOne({}, { fields: { username: 1 }, sort: {createdAt: 1}}) if oldestUser RocketChat.authz.addUsersToRoles( oldestUser._id, 'admin') console.log "No admins are found. Set #{oldestUser.username} as admin for being the oldest user" diff --git a/server/startup/migrations/v1.coffee b/server/startup/migrations/v1.coffee index be91de3ade8f..e2f1756dd10d 100644 --- a/server/startup/migrations/v1.coffee +++ b/server/startup/migrations/v1.coffee @@ -2,9 +2,9 @@ Meteor.startup -> Migrations.add version: 1 up: -> - Meteor.users.find({username: {$exists: false}, lastLogin: {$exists: true}}).forEach (user) -> + RocketChat.models.Users.find({username: {$exists: false}, lastLogin: {$exists: true}}).forEach (user) -> username = generateSuggestion(user) if username? and username.trim() isnt '' - Meteor.users.update({_id: user._id}, {$set: {username: username}}) + RocketChat.models.Users.setUsername user._id, username else - console.log "User without username", JSON.stringify(user, null, ' ') \ No newline at end of file + console.log "User without username", JSON.stringify(user, null, ' ') diff --git a/server/startup/migrations/v10.coffee b/server/startup/migrations/v10.coffee index 87db9f99225e..c441914c2b5c 100644 --- a/server/startup/migrations/v10.coffee +++ b/server/startup/migrations/v10.coffee @@ -7,10 +7,10 @@ Meteor.startup -> ### count = 0 - ChatRoom.find({'usernames.0': {$exists: true}}, {fields: {usernames: 1}}).forEach (room) -> + RocketChat.models.Rooms.find({'usernames.0': {$exists: true}}, {fields: {usernames: 1}}).forEach (room) -> newUsernames = _.uniq room.usernames if newUsernames.length isnt room.usernames.length count++ - ChatRoom.update {_id: room._id}, {$set: {usernames: newUsernames}} + RocketChat.models.Rooms.update {_id: room._id}, {$set: {usernames: newUsernames}} - console.log "Removed duplicated usernames from #{count} rooms" \ No newline at end of file + console.log "Removed duplicated usernames from #{count} rooms" diff --git a/server/startup/migrations/v11.coffee b/server/startup/migrations/v11.coffee index 5057568923ad..ed3d14cf7995 100644 --- a/server/startup/migrations/v11.coffee +++ b/server/startup/migrations/v11.coffee @@ -6,5 +6,5 @@ Meteor.startup -> # Set GENERAL room to be default ### - ChatRoom.update({_id: 'GENERAL'}, {$set: {default: true}}) - console.log "Set GENERAL room to be default" \ No newline at end of file + RocketChat.models.Rooms.update({_id: 'GENERAL'}, {$set: {default: true}}) + console.log "Set GENERAL room to be default" diff --git a/server/startup/migrations/v12.coffee b/server/startup/migrations/v12.coffee index 18b446bcf96c..bfb96bc2c0d1 100644 --- a/server/startup/migrations/v12.coffee +++ b/server/startup/migrations/v12.coffee @@ -3,11 +3,11 @@ Meteor.startup -> version: 12 up: -> # Set oldest user as admin, if none exists yet - admin = Meteor.users.findOne { admin: true }, { fields: { _id: 1 } } + admin = RocketChat.models.Users.findOneAdmin true, { fields: { _id: 1 } } unless admin # get oldest user - oldestUser = Meteor.users.findOne({}, { fields: { username: 1 }, sort: {createdAt: 1}}) + oldestUser = RocketChat.models.Users.findOne({}, { fields: { username: 1 }, sort: {createdAt: 1}}) if oldestUser Meteor.users.update {_id: oldestUser._id}, {$set: {admin: true}} - console.log "Set #{oldestUser.username} as admin for being the oldest user" \ No newline at end of file + console.log "Set #{oldestUser.username} as admin for being the oldest user" diff --git a/server/startup/migrations/v13.coffee b/server/startup/migrations/v13.coffee index be8b90dbee5d..0d7c18d745ec 100644 --- a/server/startup/migrations/v13.coffee +++ b/server/startup/migrations/v13.coffee @@ -3,5 +3,5 @@ Meteor.startup -> version: 13 up: -> # Set all current users as active - Meteor.users.update {}, { $set: { active: true } }, { multi: true } - console.log "Set all users as active" \ No newline at end of file + RocketChat.models.Users.setAllUsersActive true + console.log "Set all users as active" diff --git a/server/startup/migrations/v14.coffee b/server/startup/migrations/v14.coffee index 99549a4a12ed..2ac5724be84a 100644 --- a/server/startup/migrations/v14.coffee +++ b/server/startup/migrations/v14.coffee @@ -3,17 +3,17 @@ Meteor.startup -> version: 14 up: -> # Remove unused settings - Settings.remove { _id: "API_Piwik_URL" } - Settings.remove { _id: "API_Piwik_ID" } - - Settings.remove { _id: "Message_Edit" } - Settings.remove { _id: "Message_Delete" } - Settings.remove { _id: "Message_KeepStatusHistory" } - - Settings.update { _id: "Message_ShowEditedStatus" }, { $set: { type: "boolean", value: true } } - Settings.update { _id: "Message_ShowDeletedStatus" }, { $set: { type: "boolean", value: false } } + RocketChat.models.Settings.remove { _id: "API_Piwik_URL" } + RocketChat.models.Settings.remove { _id: "API_Piwik_ID" } - metaKeys = [ + RocketChat.models.Settings.remove { _id: "Message_Edit" } + RocketChat.models.Settings.remove { _id: "Message_Delete" } + RocketChat.models.Settings.remove { _id: "Message_KeepStatusHistory" } + + RocketChat.models.Settings.update { _id: "Message_ShowEditedStatus" }, { $set: { type: "boolean", value: true } } + RocketChat.models.Settings.update { _id: "Message_ShowDeletedStatus" }, { $set: { type: "boolean", value: false } } + + metaKeys = [ 'old': 'Meta:language' 'new': 'Meta_language' , @@ -31,12 +31,12 @@ Meteor.startup -> ] for oldAndNew in metaKeys - oldValue = Settings.findOne({_id: oldAndNew.old})?.value - newValue = Settings.findOne({_id: oldAndNew.new})?.value + oldValue = RocketChat.models.Settings.findOne({_id: oldAndNew.old})?.value + newValue = RocketChat.models.Settings.findOne({_id: oldAndNew.new})?.value if oldValue? and not newValue? - Settings.update { _id: oldAndNew.new }, { $set: { value: newValue } } - - Settings.remove { _id: oldAndNew.old } + RocketChat.models.Settings.update { _id: oldAndNew.new }, { $set: { value: newValue } } + + RocketChat.models.Settings.remove { _id: oldAndNew.old } - Settings.remove { _id: "SMTP_Security" } + RocketChat.models.Settings.remove { _id: "SMTP_Security" } diff --git a/server/startup/migrations/v15.coffee b/server/startup/migrations/v15.coffee index fda6e7b2a1e7..4ded09bff6e6 100644 --- a/server/startup/migrations/v15.coffee +++ b/server/startup/migrations/v15.coffee @@ -59,7 +59,7 @@ Meteor.startup -> n: oldChunk.n data: oldChunk.data - ChatMessage.find({$or: [{ 'urls.url': "https://demo.rocket.chat/cfs/files/Files/#{cfsRecord._id}" }, { 'urls.url': "https://rocket.chat/cfs/files/Files/#{cfsRecord._id}" }]}).forEach (message) -> + RocketChat.models.Messages.find({$or: [{ 'urls.url': "https://demo.rocket.chat/cfs/files/Files/#{cfsRecord._id}" }, { 'urls.url': "https://rocket.chat/cfs/files/Files/#{cfsRecord._id}" }]}).forEach (message) -> for urlsItem in message.urls if urlsItem.url is "https://demo.rocket.chat/cfs/files/Files/#{cfsRecord._id}" or urlsItem.url is "https://rocket.chat/cfs/files/Files/#{cfsRecord._id}" urlsItem.url = Meteor.absoluteUrl() + url @@ -68,7 +68,7 @@ Meteor.startup -> message.msg = message.msg.replace "https://demo.rocket.chat/cfs/files/Files/#{cfsRecord._id}", Meteor.absoluteUrl() + url message.msg = message.msg.replace "https://rocket.chat/cfs/files/Files/#{cfsRecord._id}", Meteor.absoluteUrl() + url - ChatMessage.update {_id: message._id}, {$set: {urls: message.urls, msg: message.msg}} + RocketChat.models.Messages.update {_id: message._id}, {$set: {urls: message.urls, msg: message.msg}} oldFilesCollection.remove _id: cfsRecord._id oldGridFSCollection.remove _id: oldGridFsFile._id diff --git a/server/startup/migrations/v16.coffee b/server/startup/migrations/v16.coffee index 2315bd2057fd..25ecafec6a9e 100644 --- a/server/startup/migrations/v16.coffee +++ b/server/startup/migrations/v16.coffee @@ -2,5 +2,4 @@ Meteor.startup -> Migrations.add version: 16 up: -> - rawMessage = ChatMessage.rawCollection() - Meteor.wrapAsync(rawMessage.dropIndex, rawMessage)({ _hidden: 1 }) + RocketChat.models.Messages.tryDropIndex({ _hidden: 1 }) diff --git a/server/startup/migrations/v17.coffee b/server/startup/migrations/v17.coffee index 38dac837a0d8..f0d1cf540bcd 100644 --- a/server/startup/migrations/v17.coffee +++ b/server/startup/migrations/v17.coffee @@ -2,8 +2,4 @@ Meteor.startup -> Migrations.add version: 17 up: -> - rawMessage = ChatMessage.rawCollection() - try - Meteor.wrapAsync(rawMessage.dropIndex, rawMessage)({ _hidden: 1 }) - catch e - console.log e + RocketChat.models.Messages.tryDropIndex({ _hidden: 1 }) diff --git a/server/startup/migrations/v18.coffee b/server/startup/migrations/v18.coffee index afddbdd631d1..f9293c59bfaa 100644 --- a/server/startup/migrations/v18.coffee +++ b/server/startup/migrations/v18.coffee @@ -26,10 +26,10 @@ Meteor.startup -> Accounts_Twitter_secret: 'Accounts_OAuth_Twitter_secret' for from, to of changes - record = Settings.findOne _id: from + record = RocketChat.models.Settings.findOne _id: from if record? delete record._id - Settings.upsert {_id: to}, record - Settings.remove _id: from + RocketChat.models.Settings.upsert {_id: to}, record + RocketChat.models.Settings.remove _id: from - ServiceConfiguration.configurations.remove({}) \ No newline at end of file + ServiceConfiguration.configurations.remove({}) diff --git a/server/startup/migrations/v19.coffee b/server/startup/migrations/v19.coffee index 02c47df293c6..db336f082494 100644 --- a/server/startup/migrations/v19.coffee +++ b/server/startup/migrations/v19.coffee @@ -18,9 +18,9 @@ Meteor.startup -> usernames = _.pluck( users, 'username').join(', ') console.log "Add #{usernames} to 'user' role".green - # Add 'moderator' role to channel/group creators - rooms = ChatRoom.find({t: {$in : ['c','p']}}).fetch() - _.each( rooms, (room) -> + # Add 'moderator' role to channel/group creators + rooms = RocketChat.models.Rooms.findByTypes(['c','p']).fetch() + _.each( rooms, (room) -> creator = room?.u?._id if creator RocketChat.authz.addUsersToRoles( creator, ['moderator'], room._id) diff --git a/server/startup/migrations/v2.coffee b/server/startup/migrations/v2.coffee index 639215ef5b00..baf7777b185d 100644 --- a/server/startup/migrations/v2.coffee +++ b/server/startup/migrations/v2.coffee @@ -2,7 +2,7 @@ Meteor.startup -> Migrations.add version: 2 up: -> - Meteor.users.find({avatarOrigin: {$exists: false}, username: {$exists: true}}).forEach (user) -> + RocketChat.models.Users.find({avatarOrigin: {$exists: false}, username: {$exists: true}}).forEach (user) -> avatars = getAvatarSuggestionForUser user services = Object.keys avatars @@ -20,6 +20,6 @@ Meteor.startup -> rs = RocketChatFile.bufferToStream new Buffer(image, 'base64') ws = RocketChatFileAvatarInstance.createWriteStream "#{user.username}.jpg", contentType ws.on 'end', Meteor.bindEnvironment -> - Meteor.users.update {_id: user._id}, {$set: {avatarOrigin: service}} + RocketChat.models.Users.setAvatarOrigin user._id, service rs.pipe(ws) diff --git a/server/startup/migrations/v3.coffee b/server/startup/migrations/v3.coffee index 5194e297b67c..90ca4b463394 100644 --- a/server/startup/migrations/v3.coffee +++ b/server/startup/migrations/v3.coffee @@ -3,16 +3,15 @@ Meteor.startup -> version: 3 up: -> - try - ChatSubscription._dropIndex 'uid_1' - try - ChatSubscription._dropIndex 'rid_1_uid_1' + + RocketChat.models.Subscriptions.tryDropIndex 'uid_1' + RocketChat.models.Subscriptions.tryDropIndex 'rid_1_uid_1' console.log 'Fixing ChatSubscription uid' - ChatSubscription.find({uid: {$exists: true}}, {nonreactive: true}).forEach (sub) -> + RocketChat.models.Subscriptions.find({uid: {$exists: true}}, {nonreactive: true}).forEach (sub) -> update = {} - user = Meteor.users.findOne(sub.uid, {fields: {username: 1}}) + user = RocketChat.models.Users.findOneById(sub.uid, {fields: {username: 1}}) if user? update.$set ?= {} update.$unset ?= {} @@ -21,13 +20,13 @@ Meteor.startup -> update.$unset.uid = 1 if Object.keys(update).length > 0 - ChatSubscription.update(sub._id, update) + RocketChat.models.Subscriptions.update(sub._id, update) console.log 'Fixing ChatRoom uids' - ChatRoom.find({'uids.0': {$exists: true}}, {nonreactive: true}).forEach (room) -> + RocketChat.models.Rooms.find({'uids.0': {$exists: true}}, {nonreactive: true}).forEach (room) -> update = {} - users = Meteor.users.find {_id: {$in: room.uids}, username: {$exists: true}}, {fields: {username: 1}} + users = RocketChat.models.Users.find {_id: {$in: room.uids}, username: {$exists: true}}, {fields: {username: 1}} usernames = users.map (user) -> return user.username @@ -36,7 +35,7 @@ Meteor.startup -> update.$set.usernames = usernames update.$unset.uids = 1 - user = Meteor.users.findOne(room.uid, {fields: {username: 1}}) + user = RocketChat.models.Users.findOneById(room.uid, {fields: {username: 1}}) if user? update.$set['u._id'] = user._id update.$set['u.username'] = user.username @@ -50,18 +49,18 @@ Meteor.startup -> oldId = room._id room._id = usernames.sort().join(',') - ChatRoom.insert(room) - ChatRoom.remove({_id: oldId}) - ChatSubscription.update({rid: oldId}, {$set: {rid: room._id}}, {multi: true}) - ChatMessage.update({rid: oldId}, {$set: {rid: room._id}}, {multi: true}) + RocketChat.models.Rooms.insert(room) + RocketChat.models.Rooms.removeById(oldId) + RocketChat.models.Subscriptions.update({rid: oldId}, {$set: {rid: room._id}}, {multi: true}) + RocketChat.models.Messages.update({rid: oldId}, {$set: {rid: room._id}}, {multi: true}) else - ChatRoom.update(room._id, update) + RocketChat.models.Rooms.update(room._id, update) console.log 'Fixing ChatMessage uid' - ChatMessage.find({uid: {$exists: true}}, {nonreactive: true}).forEach (message) -> + RocketChat.models.Messages.find({uid: {$exists: true}}, {nonreactive: true}).forEach (message) -> update = {} - user = Meteor.users.findOne(message.uid, {fields: {username: 1}}) + user = RocketChat.models.Users.findOneById(message.uid, {fields: {username: 1}}) if user? update.$set ?= {} update.$unset ?= {} @@ -70,6 +69,6 @@ Meteor.startup -> update.$unset.uid = 1 if Object.keys(update).length > 0 - ChatMessage.update(message._id, update) + RocketChat.models.Messages.update(message._id, update) console.log 'End' diff --git a/server/startup/migrations/v4.coffee b/server/startup/migrations/v4.coffee index d174c99bac81..b61f13563f77 100644 --- a/server/startup/migrations/v4.coffee +++ b/server/startup/migrations/v4.coffee @@ -3,27 +3,27 @@ Meteor.startup -> version: 4 up: -> - try ChatMessage._dropIndex 'rid_1' - try ChatSubscription._dropIndex 'u._id_1' + RocketChat.models.Messages.tryDropIndex 'rid_1' + RocketChat.models.Subscriptions.tryDropIndex 'u._id_1' console.log 'Rename rn to name' - ChatSubscription.update({rn: {$exists: true}}, {$rename: {rn: 'name'}}, {multi: true}) + RocketChat.models.Subscriptions.update({rn: {$exists: true}}, {$rename: {rn: 'name'}}, {multi: true}) console.log 'Adding names to rooms without name' - ChatRoom.find({name: ''}).forEach (item) -> + RocketChat.models.Rooms.find({name: ''}).forEach (item) -> name = Random.id().toLowerCase() - ChatRoom.update item._id, {$set: {name: name}} - ChatSubscription.update {rid: item._id}, {$set: {name: name}}, {multi: true} + RocketChat.models.Rooms.setNameById item._id, name + RocketChat.models.Subscriptions.update {rid: item._id}, {$set: {name: name}}, {multi: true} console.log 'Making room names unique' - ChatRoom.find().forEach (room) -> - ChatRoom.find({name: room.name, _id: {$ne: room._id}}).forEach (item) -> + RocketChat.models.Rooms.find().forEach (room) -> + RocketChat.models.Rooms.find({name: room.name, _id: {$ne: room._id}}).forEach (item) -> name = room.name + '-' + Random.id(2).toLowerCase() - ChatRoom.update item._id, {$set: {name: name}} - ChatSubscription.update {rid: item._id}, {$set: {name: name}}, {multi: true} + RocketChat.models.Rooms.setNameById item._id, name + RocketChat.models.Subscriptions.update {rid: item._id}, {$set: {name: name}}, {multi: true} console.log 'End' diff --git a/server/startup/migrations/v5.coffee b/server/startup/migrations/v5.coffee index c2dc458de6a4..b3886f4dea78 100644 --- a/server/startup/migrations/v5.coffee +++ b/server/startup/migrations/v5.coffee @@ -4,61 +4,61 @@ Meteor.startup -> up: -> console.log 'Dropping test rooms with less than 2 messages' - ChatRoom.find({msgs: {'$lt': 2}}).forEach (room) -> + RocketChat.models.Rooms.find({msgs: {'$lt': 2}}).forEach (room) -> console.log 'Dropped: ', room.name - ChatRoom.remove room._id - ChatMessage.remove {rid: room._id} - ChatSubscription.remove {rid: room._id} + RocketChat.models.Rooms.removeById room._id + RocketChat.models.Messages.removeByRoomId room._id + RocketChat.models.Subscriptions.removeByRoomId room._id console.log 'Dropping test rooms with less than 2 user' - ChatRoom.find({usernames: {'$size':1}}).forEach (room) -> + RocketChat.models.Rooms.find({usernames: {'$size':1}}).forEach (room) -> console.log 'Dropped: ', room.name - ChatRoom.remove room._id - ChatMessage.remove {rid: room._id} - ChatSubscription.remove {rid: room._id} + RocketChat.models.Rooms.removeById room._id + RocketChat.models.Messages.removeByRoomId room._id + RocketChat.models.Subscriptions.removeByRoomId room._id console.log 'Adding username to all users' - Meteor.users.find({ 'username': {'$exists':0}, 'emails': {'$exists':1} }).forEach (user) -> + RocketChat.models.Users.find({ 'username': {'$exists':0}, 'emails': {'$exists':1} }).forEach (user) -> newUserName = user.emails[0].address.split("@")[0] - if Meteor.users.findOne({'username':newUserName}) + if RocketChat.models.Users.findOneByUsername(newUserName) newUserName = newUserName + Math.floor((Math.random() * 10) + 1) - if Meteor.users.findOne({'username':newUserName}) + if RocketChat.models.Users.findOneByUsername(newUserName) newUserName = newUserName + Math.floor((Math.random() * 10) + 1) - if Meteor.users.findOne({'username':newUserName}) + if RocketChat.models.Users.findOneByUsername(newUserName) newUserName = newUserName + Math.floor((Math.random() * 10) + 1); console.log 'Adding: username ' + newUserName + ' to all user ' + user._id; - Meteor.users.update({'_id':user._id},{'$set':{'username':newUserName}}); + RocketChat.models.Users.setUsername user._id, newUserName console.log 'Fixing _id of direct messages rooms' - ChatRoom.find({'t': 'd'}).forEach (room) -> + RocketChat.models.Rooms.findByType('d').forEach (room) -> newId = '' - id0 = Meteor.users.findOne({ 'username': room.usernames[0] })._id - id1 = Meteor.users.findOne({ 'username': room.usernames[1] })._id + id0 = RocketChat.models.Users.findOneByUsername(room.usernames[0])._id + id1 = RocketChat.models.Users.findOneByUsername(room.usernames[1])._id ids = [id0,id1] newId = ids.sort().join('') if (newId != room._id) console.log 'Fixing: _id ' + room._id + ' to ' + newId - ChatSubscription.update({'rid':room._id},{'$set':{'rid':newId}},{'multi':1}) - ChatMessage.update({'rid':room._id},{'$set':{'rid':newId}},{'multi':1}) - ChatRoom.remove({'_id':room._id}) + RocketChat.models.Subscriptions.update({'rid':room._id},{'$set':{'rid':newId}},{'multi':1}) + RocketChat.models.Messages.update({'rid':room._id},{'$set':{'rid':newId}},{'multi':1}) + RocketChat.models.Rooms.removeById(room._id) room._id = newId - ChatRoom.insert(room) - ChatSubscription.update({'rid':room._id,'u._id':id0},{'$set':{'name':room.usernames[1]}}) - ChatSubscription.update({'rid':room._id,'u._id':id1},{'$set':{'name':room.usernames[0]}}) + RocketChat.models.Rooms.insert(room) + RocketChat.models.Subscriptions.update({'rid':room._id,'u._id':id0},{'$set':{'name':room.usernames[1]}}) + RocketChat.models.Subscriptions.update({'rid':room._id,'u._id':id1},{'$set':{'name':room.usernames[0]}}) console.log 'Adding u.username to all documents' - Meteor.users.find({},{'username':1}).forEach (user) -> + RocketChat.models.Users.find({},{'username':1}).forEach (user) -> console.log 'Adding: u.username ' + user.username + ' to all document' - ChatRoom.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) - ChatSubscription.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) - ChatMessage.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) - ChatMessage.update({'uid':user._id},{'$set':{'u':user}},{'multi':1}) - ChatMessage.update({'by':user._id},{'$set':{'u':user}},{'multi':1}) - ChatMessage.update({'uid':{'$exists':1}},{'$unset':{'uid':1,'by':1}},{'multi':1}) + RocketChat.models.Rooms.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) + RocketChat.models.Subscriptions.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) + RocketChat.models.Messages.update({'u._id':user._id},{'$set':{'u.username':user.username}},{'multi':1}) + RocketChat.models.Messages.update({'uid':user._id},{'$set':{'u':user}},{'multi':1}) + RocketChat.models.Messages.update({'by':user._id},{'$set':{'u':user}},{'multi':1}) + RocketChat.models.Messages.update({'uid':{'$exists':1}},{'$unset':{'uid':1,'by':1}},{'multi':1}) console.log 'End' diff --git a/server/startup/migrations/v6.coffee b/server/startup/migrations/v6.coffee index 4c84a094b22d..a9a505ee0031 100644 --- a/server/startup/migrations/v6.coffee +++ b/server/startup/migrations/v6.coffee @@ -4,13 +4,13 @@ Meteor.startup -> up: -> console.log 'Changin _id of #general channel room from XXX to GENERAL' - room = ChatRoom.findOne('name':'general') + room = RocketChat.models.Rooms.findOneByName('general') if room?._id is not 'GENERAL' - ChatSubscription.update({'rid':room._id},{'$set':{'rid':'GENERAL'}},{'multi':1}) - ChatMessage.update({'rid':room._id},{'$set':{'rid':'GENERAL'}},{'multi':1}) - ChatRoom.remove({'_id':room._id}) + RocketChat.models.Subscriptions.update({'rid':room._id},{'$set':{'rid':'GENERAL'}},{'multi':1}) + RocketChat.models.Messages.update({'rid':room._id},{'$set':{'rid':'GENERAL'}},{'multi':1}) + RocketChat.models.Rooms.removeById(room._id) delete room._id - ChatRoom.upsert({'_id':'GENERAL'},{$set: room}) + RocketChat.models.Rooms.upsert({'_id':'GENERAL'},{$set: room}) console.log 'End' diff --git a/server/startup/migrations/v7.coffee b/server/startup/migrations/v7.coffee index edad19d6cf9d..2f85268ffef7 100644 --- a/server/startup/migrations/v7.coffee +++ b/server/startup/migrations/v7.coffee @@ -4,7 +4,7 @@ Meteor.startup -> up: -> console.log 'Populate urls in messages' - query = ChatMessage.find({ 'urls.0': { $exists: true } }) + query = RocketChat.models.Messages.find({ 'urls.0': { $exists: true } }) count = query.count() query.forEach (message, index) -> console.log "#{index + 1} / #{count}" diff --git a/server/startup/migrations/v8.coffee b/server/startup/migrations/v8.coffee index 637e3f9a7ff1..87d210f5ad98 100644 --- a/server/startup/migrations/v8.coffee +++ b/server/startup/migrations/v8.coffee @@ -3,13 +3,13 @@ Meteor.startup -> version: 8 up: -> console.log 'Load old settings record' - settings = Settings.findOne({ _id: 'settings' }) + settings = RocketChat.models.Settings.findOne({ _id: 'settings' }) if settings - Settings.insert { _id: 'CDN_PREFIX', value: settings.CDN_PREFIX, type: 'string', group: 'General' } if settings.CDN_PREFIX? - Settings.insert { _id: 'MAIL_URL', value: settings.ENV.MAIL_URL, type: 'string', group: 'SMTP' } if settings.ENV?.MAIL_URL? - Settings.insert { _id: 'Accounts_denyUnverifiedEmails', value: settings.denyUnverifiedEmails, type: 'boolean', group: 'Accounts' } if settings.denyUnverifiedEmails? - Settings.insert { _id: 'KADIRA_APP_ID', value: settings.kadira.appId, type: 'string', group: 'API' } if settings.kadira?.appId? - Settings.insert { _id: 'KADIRA_APP_SECRET', value: settings.kadira.appSecret, type: 'string', group: 'API' } if settings.kadira?.appSecret? - Settings.insert { _id: 'avatarStore_type', value: settings.public.avatarStore.type, type: 'string', group: 'API' } if settings.public?.avatarStore?.type? - Settings.insert { _id: 'avatarStore_path', value: settings.public.avatarStore.path, type: 'string', group: 'API' } if settings.public?.avatarStore?.path? - Settings.remove { _id: 'settings' } \ No newline at end of file + RocketChat.models.Settings.insert { _id: 'CDN_PREFIX', value: settings.CDN_PREFIX, type: 'string', group: 'General' } if settings.CDN_PREFIX? + RocketChat.models.Settings.insert { _id: 'MAIL_URL', value: settings.ENV.MAIL_URL, type: 'string', group: 'SMTP' } if settings.ENV?.MAIL_URL? + RocketChat.models.Settings.insert { _id: 'Accounts_denyUnverifiedEmails', value: settings.denyUnverifiedEmails, type: 'boolean', group: 'Accounts' } if settings.denyUnverifiedEmails? + RocketChat.models.Settings.insert { _id: 'KADIRA_APP_ID', value: settings.kadira.appId, type: 'string', group: 'API' } if settings.kadira?.appId? + RocketChat.models.Settings.insert { _id: 'KADIRA_APP_SECRET', value: settings.kadira.appSecret, type: 'string', group: 'API' } if settings.kadira?.appSecret? + RocketChat.models.Settings.insert { _id: 'avatarStore_type', value: settings.public.avatarStore.type, type: 'string', group: 'API' } if settings.public?.avatarStore?.type? + RocketChat.models.Settings.insert { _id: 'avatarStore_path', value: settings.public.avatarStore.path, type: 'string', group: 'API' } if settings.public?.avatarStore?.path? + RocketChat.models.Settings.remove { _id: 'settings' } diff --git a/server/startup/migrations/v9.coffee b/server/startup/migrations/v9.coffee index e83e78724394..45628dd5647e 100644 --- a/server/startup/migrations/v9.coffee +++ b/server/startup/migrations/v9.coffee @@ -5,27 +5,27 @@ Meteor.startup -> # Migrate existing source collection data to target collection # target collection is defined in collections.coffee using the new collection name # source collection is dropped after data migration - toMigrate = [ + toMigrate = [ { source: new Meteor.Collection 'data.ChatRoom' - target: ChatRoom + target: RocketChat.models.Rooms.model } { source: new Meteor.Collection 'data.ChatSubscription' - target: ChatSubscription + target: RocketChat.models.Subscriptions.model } { source: new Meteor.Collection 'data.ChatMessage' - target: ChatMessage + target: RocketChat.models.Messages.model } { source: new Meteor.Collection 'settings' - target: Settings + target: Settings } { # this collection may not exit source: new Meteor.Collection 'oembed_cache' - target: OEmbed.cache + target: OEmbed.cache } ] @@ -47,7 +47,7 @@ Meteor.startup -> ) # Note: the following would have been much easier, but didn't work. The serverside - # data was not published to the client for some reason. + # data was not published to the client for some reason. # newName = target.rawCollection().collectionName - # Meteor.wrapAsync(rawSource.rename, rawSource )(newName, {dropTarget:true}) + # Meteor.wrapAsync(rawSource.rename, rawSource )(newName, {dropTarget:true}) diff --git a/server/stream/messages.coffee b/server/stream/messages.coffee index 5cf342530488..4812a7e515a0 100644 --- a/server/stream/messages.coffee +++ b/server/stream/messages.coffee @@ -35,7 +35,7 @@ Meteor.startup -> if not RocketChat.settings.get 'Message_ShowEditedStatus' options.fields = { ets: 0 } - ChatMessage.find(filter, options).observe + RocketChat.models.Messages.findVisibleCreatedOrEditedAfterTimestamp(new Date(), options).observe added: (record) -> msgStream.emit record.rid, record