2012-07-04 03:48:01 +02:00
|
|
|
class Message < ActiveRecord::Base
|
|
|
|
belongs_to :recipient,
|
|
|
|
:class_name => "User",
|
|
|
|
:foreign_key => "recipient_user_id"
|
|
|
|
belongs_to :author,
|
|
|
|
:class_name => "User",
|
|
|
|
:foreign_key => "author_user_id"
|
|
|
|
|
|
|
|
validates_presence_of :recipient
|
|
|
|
validates_presence_of :author
|
|
|
|
|
|
|
|
attr_accessor :recipient_username
|
|
|
|
|
|
|
|
attr_accessible :recipient_username, :subject, :body
|
|
|
|
|
|
|
|
validates_length_of :subject, :in => 1..150
|
|
|
|
validates_length_of :body, :maximum => (64 * 1024)
|
2013-01-23 07:32:45 +01:00
|
|
|
|
2013-07-20 05:05:00 +02:00
|
|
|
before_validation :assign_short_id,
|
|
|
|
:on => :create
|
2012-07-04 03:48:01 +02:00
|
|
|
after_create :deliver_reply_notifications
|
|
|
|
after_save :update_unread_counts
|
2013-01-24 21:06:10 +01:00
|
|
|
after_save :check_for_both_deleted
|
2012-07-04 03:48:01 +02:00
|
|
|
|
2013-01-23 07:32:45 +01:00
|
|
|
def assign_short_id
|
|
|
|
self.short_id = ShortId.new(self.class).generate
|
2012-07-04 03:48:01 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def check_for_both_deleted
|
2013-01-24 21:06:10 +01:00
|
|
|
if self.deleted_by_author? && self.deleted_by_recipient?
|
2012-07-04 03:48:01 +02:00
|
|
|
self.destroy
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_unread_counts
|
|
|
|
self.recipient.update_unread_message_count!
|
|
|
|
end
|
2013-01-23 07:32:45 +01:00
|
|
|
|
2012-07-04 03:48:01 +02:00
|
|
|
def deliver_reply_notifications
|
|
|
|
begin
|
|
|
|
if self.recipient.email_messages?
|
|
|
|
EmailMessage.notify(self, self.recipient).deliver
|
|
|
|
end
|
|
|
|
|
|
|
|
if self.recipient.pushover_messages? &&
|
|
|
|
self.recipient.pushover_user_key.present?
|
|
|
|
Pushover.push(self.recipient.pushover_user_key,
|
|
|
|
self.recipient.pushover_device, {
|
2013-06-30 08:29:51 +02:00
|
|
|
:title => "#{Rails.application.name} message from " <<
|
|
|
|
"#{self.author.username}: #{self.subject}",
|
2012-07-04 03:48:01 +02:00
|
|
|
:message => self.plaintext_body,
|
|
|
|
:url => self.url,
|
|
|
|
:url_title => "Reply to #{self.author.username}",
|
|
|
|
})
|
|
|
|
end
|
|
|
|
rescue
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def recipient_username=(username)
|
|
|
|
self.recipient_user_id = nil
|
|
|
|
|
|
|
|
if u = User.find_by_username(username)
|
|
|
|
self.recipient_user_id = u.id
|
|
|
|
@recipient_username = username
|
|
|
|
else
|
|
|
|
errors.add(:recipient_username, "is not a valid user")
|
|
|
|
end
|
|
|
|
end
|
2012-11-08 04:58:10 +01:00
|
|
|
|
2012-07-04 03:48:01 +02:00
|
|
|
def linkified_body
|
2012-07-07 00:52:32 +02:00
|
|
|
Markdowner.to_html(self.body)
|
2012-07-04 03:48:01 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def plaintext_body
|
|
|
|
# TODO: linkify then strip tags and convert entities back
|
|
|
|
self.body.to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
def url
|
|
|
|
Rails.application.routes.url_helpers.root_url + "messages/#{self.short_id}"
|
|
|
|
end
|
|
|
|
end
|