]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api/changeset_comments_controller.rb
Merge pull request #6394 from openstreetmap/dependabot/github_actions/ruby/setup...
[rails.git] / app / controllers / api / changeset_comments_controller.rb
1 # frozen_string_literal: true
2
3 module Api
4   class ChangesetCommentsController < ApiController
5     include QueryMethods
6
7     before_action :check_api_writable, :except => [:index]
8     before_action :authorize, :except => [:index]
9
10     authorize_resource
11
12     before_action :require_public_data, :only => [:create]
13
14     before_action :set_request_formats
15
16     ##
17     # show all comments or search for a subset
18     def index
19       @comments = ChangesetComment.includes(:author).where(:visible => true).order(:created_at => :desc)
20       @comments = query_conditions_time(@comments)
21       @comments = query_conditions_user(@comments, :author)
22       @comments = query_limit(@comments)
23     end
24
25     ##
26     # Add a comment to a changeset
27     def create
28       # Check the arguments are sane
29       raise OSM::APIBadUserInput, "No id was given" unless params[:changeset_id]
30       raise OSM::APIBadUserInput, "No text was given" if params[:text].blank?
31       raise OSM::APIRateLimitExceeded if rate_limit_exceeded?
32
33       # Extract the arguments
34       changeset_id = params[:changeset_id].to_i
35       body = params[:text]
36
37       # Find the changeset and check it is valid
38       changeset = Changeset.find(changeset_id)
39       raise OSM::APIChangesetNotYetClosedError, changeset if changeset.open?
40
41       # Add a comment to the changeset
42       comment = changeset.comments.create(:changeset => changeset,
43                                           :body => body,
44                                           :author => current_user)
45
46       # Notify current subscribers of the new comment
47       changeset.subscribers.visible.each do |user|
48         UserMailer.changeset_comment_notification(comment, user).deliver_later if current_user != user
49       end
50
51       # Add the commenter to the subscribers if necessary
52       changeset.subscribers << current_user unless changeset.subscribers.exists?(current_user.id)
53
54       # Return a copy of the updated changeset
55       @changeset = changeset
56       render "api/changesets/show"
57
58       respond_to do |format|
59         format.xml
60         format.json
61       end
62     end
63
64     private
65
66     ##
67     # Check if the current user has exceed the rate limit for comments
68     def rate_limit_exceeded?
69       recent_comments = current_user.changeset_comments.where(:created_at => (Time.now.utc - 1.hour)..).count
70
71       recent_comments >= current_user.max_changeset_comments_per_hour
72     end
73   end
74 end