]> git.openstreetmap.org Git - rails.git/blob - app/models/message.rb
Merge remote-tracking branch 'upstream/pull/2225'
[rails.git] / app / models / message.rb
1 # == Schema Information
2 #
3 # Table name: messages
4 #
5 #  id                :bigint(8)        not null, primary key
6 #  from_user_id      :bigint(8)        not null
7 #  title             :string           not null
8 #  body              :text             not null
9 #  sent_on           :datetime         not null
10 #  message_read      :boolean          default(FALSE), not null
11 #  to_user_id        :bigint(8)        not null
12 #  to_user_visible   :boolean          default(TRUE), not null
13 #  from_user_visible :boolean          default(TRUE), not null
14 #  body_format       :enum             default("markdown"), not null
15 #
16 # Indexes
17 #
18 #  messages_from_user_id_idx  (from_user_id)
19 #  messages_to_user_id_idx    (to_user_id)
20 #
21 # Foreign Keys
22 #
23 #  messages_from_user_id_fkey  (from_user_id => users.id)
24 #  messages_to_user_id_fkey    (to_user_id => users.id)
25 #
26
27 class Message < ActiveRecord::Base
28   belongs_to :sender, :class_name => "User", :foreign_key => :from_user_id
29   belongs_to :recipient, :class_name => "User", :foreign_key => :to_user_id
30
31   validates :title, :presence => true, :utf8 => true, :length => 1..255
32   validates :body, :sent_on, :sender, :recipient, :presence => true
33   validates :title, :body, :characters => true
34
35   def self.from_mail(mail, from, to)
36     if mail.multipart?
37       if mail.text_part
38         body = mail.text_part.decoded
39       elsif mail.html_part
40         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
41       end
42     elsif mail.text? && mail.sub_type == "html"
43       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
44     else
45       body = mail.decoded
46     end
47
48     Message.new(
49       :sender => from,
50       :recipient => to,
51       :sent_on => mail.date.new_offset(0),
52       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
53       :body => body,
54       :body_format => "text"
55     )
56   end
57
58   def body
59     RichText.new(self[:body_format], self[:body])
60   end
61
62   def digest
63     md5 = Digest::MD5.new
64     md5 << from_user_id.to_s
65     md5 << to_user_id.to_s
66     md5 << sent_on.xmlschema
67     md5 << title
68     md5 << body
69     md5.hexdigest
70   end
71 end