docbrown/app/controllers/messages_controller.rb
rhymes e588fa7ece Code cleanups (#659)
* Initial automatic cleanup with rubocop

* Fix syntax error introduced by rubocop

* Cleanup seeds file

* Cleanup lib folder

* Exclude bin folder because it contains auto generated files

* Make Rubocop a little bit more chatty

* Block length should not include comments in the count

* Cleanup config folder

* Cleanup specs

* Updated Rubocop version and generated a todo file

* Fix broken ArticlesApi spec

* Fix tests

* Restored rubocop pre-commit hook
2018-08-07 11:00:13 -04:00

74 lines
2.1 KiB
Ruby

class MessagesController < ApplicationController
before_action :authenticate_user!
def create
@message = Message.new(message_params)
@message.user_id = current_user.id
authorize @message
success = false
if @message.valid?
message_json = create_pusher_payload(@message)
Pusher.trigger(@message.chat_channel.pusher_channels, "message-created", message_json)
end
if @message.save
begin
@message.delay.send_push
success = true
rescue Pusher::Error => e
logger.info "PUSHER ERROR: #{e.message}"
end
if success
render json: { status: "success", message: "Message created" }, status: 201
else
error_message = "Message created but could not trigger Pusher"
render json: { status: "error", message: error_message }, status: 201
end
else
render json: {
status: "error",
message: {
chat_channel_id: @message.chat_channel_id,
message: @message.errors.full_messages,
type: "error",
},
}, status: 401
end
end
private
def create_pusher_payload(new_message)
{
user_id: new_message.user.id,
chat_channel_id: new_message.chat_channel.id,
chat_channel_adjusted_slug: new_message.chat_channel.adjusted_slug(current_user, "sender"),
username: new_message.user.username,
profile_image_url: ProfileImage.new(new_message.user).get(90),
message: new_message.message_html,
timestamp: Time.now,
color: new_message.preferred_user_color,
reception_method: "pushed",
}.to_json
end
def message_params
params.require(:message).permit(:message_markdown, :user_id, :chat_channel_id)
end
def user_not_authorized
respond_to do |format|
format.json do
render json: {
status: "error",
message: {
chat_channel_id: message_params[:chat_channel_id],
message: "You can not do that because you are banned",
type: "error",
},
}, status: 401
end
end
end
end