1 # The MessagesController is the RESTful interface to Message objects
4 class MessagesController < ApiController
5 before_action :authorize
7 before_action :check_api_writable, :only => [:create, :update, :destroy]
8 before_action :check_api_readable, :except => [:create, :update, :destroy]
12 before_action :set_request_formats
14 # Dump the details on a message given in params[:id]
16 @message = Message.includes(:sender, :recipient).find(params[:id])
18 raise OSM::APIAccessDenied if current_user.id != @message.from_user_id && current_user.id != @message.to_user_id
21 respond_to do |format|
27 # Create a new message from current user
29 # Check the arguments are sane
30 raise OSM::APIBadUserInput, "No title was given" if params[:title].blank?
31 raise OSM::APIBadUserInput, "No body was given" if params[:body].blank?
33 # Extract the arguments
34 if params[:recipient_id]
35 recipient_id = params[:recipient_id].to_i
36 recipient = User.find(recipient_id)
37 elsif params[:recipient]
38 recipient_display_name = params[:recipient]
39 recipient = User.find_by(:display_name => recipient_display_name)
41 raise OSM::APIBadUserInput, "No recipient was given"
44 raise OSM::APIRateLimitExceeded if current_user.sent_messages.where(:sent_on => Time.now.utc - 1.hour..).count >= current_user.max_messages_per_hour
46 @message = Message.new(:sender => current_user,
47 :recipient => recipient,
48 :sent_on => Time.now.utc,
49 :title => params[:title],
50 :body => params[:body],
51 :body_format => "markdown")
54 UserMailer.message_notification(@message).deliver_later if @message.notify_recipient?
56 # Return a copy of the new message
57 respond_to do |format|
58 format.xml { render :action => :show }
59 format.json { render :action => :show }
63 # Update read status of a message
65 @message = Message.find(params[:id])
66 read_status_idx = %w[true false].index params[:read_status]
68 raise OSM::APIBadUserInput, "Invalid value of `read_status` was given" if read_status_idx.nil?
69 raise OSM::APIAccessDenied unless current_user.id == @message.to_user_id
71 @message.message_read = read_status_idx.zero?
74 # Return a copy of the message
75 respond_to do |format|
76 format.xml { render :action => :show }
77 format.json { render :action => :show }
81 # Delete message by marking it as not visible for the current user
83 @message = Message.find(params[:id])
84 if current_user.id == @message.from_user_id
85 @message.from_user_visible = false
86 elsif current_user.id == @message.to_user_id
87 @message.to_user_visible = false
89 raise OSM::APIAccessDenied
94 # Return a copy of the message
95 respond_to do |format|
96 format.xml { render :action => :show }
97 format.json { render :action => :show }