]> git.openstreetmap.org Git - rails.git/blob - app/models/message.rb
Use ejs templates in browse JS
[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   attr_accessible :title, :body
13
14   after_initialize :set_defaults
15
16   def self.from_mail(mail, from, to)
17     if mail.multipart?
18       if mail.text_part
19         body = mail.text_part.decoded
20       elsif mail.html_part
21         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
22       end
23     elsif mail.text? and mail.sub_type == "html"
24       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
25     else
26       body = mail.decoded
27     end
28
29     message = Message.new({
30       :sender => from,
31       :recipient => to,
32       :sent_on => mail.date.new_offset(0),
33       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
34       :body => body,
35       :body_format => "text"
36     }, :without_protection => true)
37   end
38
39   def body
40     RichText.new(read_attribute(:body_format), read_attribute(:body))
41   end
42
43   def digest
44     md5 = Digest::MD5.new
45     md5 << from_user_id.to_s
46     md5 << to_user_id.to_s
47     md5 << sent_on.xmlschema
48     md5 << title
49     md5 << body
50     md5.hexdigest
51   end
52
53 private
54
55   def set_defaults
56     self.body_format = "markdown" unless self.attribute_present?(:body_format)
57   end
58 end