Jonathan Gnagy's Blog

Rails for everyone!

Listing all entries tagged 'jabber'. Feed

XMPP with Rails

In the beginning, my blog didn’t have any way to notify me when someone comments on an entry. After a while, I added an ActionMailer class (called Notifier) to email me when a comment is saved. Realizing that this might open up the door for people to spam me, I added some very basic spam checking, looking for certain inappropriate key words through regular expression matching. Maybe some day I’ll actually try and tie-in Spamassassin or something.

Today, I added a couple more advancements in regards to comments. Now, it also sends me an Instant Message through Jabber (XMPP) notifying me of a new comment. I also decided to move the sending of the email and the instant message to its own thread because I noticed some slowness when testing new comments. Now things are fast and smooth again.

Here’s the code I used to make the IM and email happen:

Add this to the Comment model:

1
2
3
4
5
6
7
...
  protected
  def validate
    SPAM_REGEXES.each do |r|
      errors.add("body", "fails SPAM checks") if body.match(r)
    end
  end

Add this to the Comment controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
    if @comment.save
      t = Thread.new do
        Notifier.deliver_comment_notification(@comment.entry.author, @comment)
        begin
          # Connect to the server and set presence to available for chat.
          client = Jabber::Simple.new('jlg_blog_bot@jabber.org/blog', JABBER_PASSWORD.to_s)
          client.deliver(
            @comment.entry.author.email, 
            "You have a new comment on your blog entry titled '#{@comment.entry.title}'",
            :normal
          )
          sleep(1)
          client.disconnect
          logger.info "Sent XMPP message about: '#{@comment.entry.title}'"
        rescue
          logger.warn "Sending of XMPP message failed..."
        end
      end # new thread
    else
      # If the comment wasn't saved, it was probably marked as spam
      flash[:warn] = "Your comment was not saved. Perhaps it was flagged as spam."
    end
...

You still need to modify the ‘config/environment.rb’ file to include definitions for JABBER_PASSWORD and SPAM_REGEXES.