]> git.openstreetmap.org Git - rails.git/blob - app/models/message.rb
Replace deprecated finder methods
[rails.git] / app / models / message.rb
1 require 'validators'
2
3 class Message < ActiveRecord::Base
4   belongs_to :sender, :class_name => "User", :foreign_key => :from_user_id
5   belongs_to :recipient, :class_name => "User", :foreign_key => :to_user_id
6
7   validates_presence_of :title, :body, :sent_on, :sender, :recipient
8   validates_length_of :title, :within => 1..255
9   validates_inclusion_of :message_read, :in => [ true, false ]
10   validates_as_utf8 :title
11
12   after_initialize :set_defaults
13
14   def self.from_mail(mail, from, to)
15     if mail.multipart?
16       if mail.text_part
17         body = mail.text_part.decoded
18       elsif mail.html_part
19         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
20       end
21     elsif mail.text? and mail.sub_type == "html"
22       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
23     else
24       body = mail.decoded
25     end
26
27     message = Message.new(
28       :sender => from,
29       :recipient => to,
30       :sent_on => mail.date.new_offset(0),
31       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
32       :body => body,
33       :body_format => "text"
34     )
35   end
36
37   def body
38     RichText.new(read_attribute(:body_format), read_attribute(:body))
39   end
40
41   def digest
42     md5 = Digest::MD5.new
43     md5 << from_user_id.to_s
44     md5 << to_user_id.to_s
45     md5 << sent_on.xmlschema
46     md5 << title
47     md5 << body
48     md5.hexdigest
49   end
50
51 private
52
53   def set_defaults
54     self.body_format = "markdown" unless self.attribute_present?(:body_format)
55   end
56 end