Skip to content
Snippets Groups Projects
sendMessage.coffee 2.24 KiB
Newer Older
Gabriel Engel's avatar
Gabriel Engel committed
	sendMessage: (message) ->
		console.log '[methods] sendMessage -> '.green, 'userId:', Meteor.userId(), 'arguments:', arguments

		if not Meteor.userId()
			throw new Meteor.Error('invalid-user', "[methods] sendMessage -> Invalid user")

Gabriel Engel's avatar
Gabriel Engel committed
		if not Meteor.call 'canAccessRoom', message.rid, Meteor.userId()
			return false
		message.u = Meteor.users.findOne Meteor.userId(), fields: username: 1
		message.ts = new Date()
		message = RocketChat.callbacks.run 'beforeSaveMessage', message
		console.log "message", message
Gabriel Engel's avatar
Gabriel Engel committed

		###
		Defer other updated as their return is not interesting to the user
		###
		Meteor.defer ->

			###
			Update all the room activity tracker fields
			###
			ChatRoom.update
				# only subscriptions to the same room
				rid: message.rid
			,
				# update the last message timestamp
				$set:
					lm: message.ts
Gabriel Engel's avatar
Gabriel Engel committed
				# increate the messages counter
				$inc:
					msgs: 1

			message.mentions?.forEach (mention) ->
				###
				Update all other subscriptions of mentioned users to alert their owners and incrementing
				the unread counter for mentions and direct messages
				###
				ChatSubscription.update
					# only subscriptions to the same room
					rid: message.rid
					# not the msg owner
					'u._id': mention._id
				,
					$set:
						# alert de user
						alert: true
						# open the room for the user
						open: true
					# increment undear couter
					$inc:
						unread: 1
				,
					# make sure we alert all matching subscription
					multi: true
			Update all other subscriptions to alert their owners but witout incrementing
Gabriel Engel's avatar
Gabriel Engel committed
			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: false
				# not the msg owner
				'u._id':
					$ne: message.u._id
Gabriel Engel's avatar
Gabriel Engel committed
			,
				$set:
					# alert de user
					alert: true
					# open the room for the user
					open: true
			,
				# make sure we alert all matching subscription
				multi: true

		###
		Save the message. If there was already a typing record, update it.
		###
Gabriel Engel's avatar
Gabriel Engel committed
		ChatMessage.upsert
				rid: message.rid
				t: 't'
				$and: [{ 'u._id': message.u._id }]
			$set: message