about summary refs log tree commit diff stats
path: root/app/controllers/comments_controller.rb
blob: 368f5872bcc2bde7d2bc481e99e607d0281b0b2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class CommentsController < ApplicationController
  def create
    @blog = Blog.find_by_slug(params[:slug])

    raise ActiveRecord::RecordNotFound unless @blog
    raise ActiveRecord::RecordNotFound unless @blog.published

    @comment = @blog.comments.new(comment_params)
    @comment.request_ip = request.ip
    @comment.user_agent = request.user_agent
    @comment.referrer = request.referrer

    unless @comment.valid?
      flash.alert = "Error posting comment."
      render "blogs/show"
      return
    end

    akismet_vars = %w{ HTTP_ACCEPT HTTP_ACCEPT_ENCODING }
    akismet_params = {
      type: "comment",
      text: @comment.body,
      created_at: DateTime.now,
      author: @comment.username,
      author_email: @comment.email,
      author_url: @comment.website,
      post_url: url_for(@comment.blog),
      post_modified_at: @comment.blog.updated_at,
      referrer: @comment.referrer,
      env: request.env.slice(*akismet_vars)
    }

    is_spam, is_blatant = Akismet.check(@comment.request_ip, @comment.user_agent, akismet_params)

    if is_blatant
      # I am lying.
      flash.notice = "Comment submitted successfully! It will need to be moderated before it shows up on the blog."
    else
      if is_spam
        @comment.status = :pending
        flash_message = "Comment submitted successfully! It will need to be moderated before it shows up on the blog."
      else
        @comment.status = :published
        flash_message = "Comment posted successfully!"
      end

      if @comment.save
        flash.notice = flash_message

        if @comment.status == :published
          CommentMailer.with(comment: @comment).new_comment_email.deliver_later

          if @comment.reply_to and @comment.reply_to.email != @comment.blog.user.email
            CommentMailer.with(comment: @comment).reply_comment_email.deliver_later
          end
        else
          CommentMailer.with(comment: @comment).new_pending_comment_email.deliver_later
        end
      else
        flash.alert = "Error posting comment."
      end
    end

    redirect_to @comment.blog
  end

  private

    def comment_params
      params.require(:comment).permit(:username, :email, :website, :body, :reply_to_id)
    end
end