]> git.openstreetmap.org Git - rails.git/blob - app/models/message.rb
65c2d29eddc9cafc9792ebb4dd385c0e44e2022b
[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   def self.from_mail(mail, from, to)
13     if mail.multipart?
14       if mail.text_part
15         body = mail.text_part.decoded
16       elsif mail.html_part
17         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
18       end
19     elsif mail.text? && mail.sub_type == "html"
20       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
21     else
22       body = mail.decoded
23     end
24
25     Message.new(
26       :sender => from,
27       :recipient => to,
28       :sent_on => mail.date.new_offset(0),
29       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
30       :body => body,
31       :body_format => "text"
32     )
33   end
34
35   def body
36     RichText.new(read_attribute(:body_format), read_attribute(:body))
37   end
38
39   def digest
40     md5 = Digest::MD5.new
41     md5 << from_user_id.to_s
42     md5 << to_user_id.to_s
43     md5 << sent_on.xmlschema
44     md5 << title
45     md5 << body
46     md5.hexdigest
47   end
48 end