]> git.openstreetmap.org Git - rails.git/blob - app/models/message.rb
Merge remote-tracking branch 'upstream/pull/4720'
[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 #  muted             :boolean          default(FALSE), not null
16 #
17 # Indexes
18 #
19 #  messages_from_user_id_idx  (from_user_id)
20 #  messages_to_user_id_idx    (to_user_id)
21 #
22 # Foreign Keys
23 #
24 #  messages_from_user_id_fkey  (from_user_id => users.id)
25 #  messages_to_user_id_fkey    (to_user_id => users.id)
26 #
27
28 class Message < ApplicationRecord
29   belongs_to :sender, :class_name => "User", :foreign_key => :from_user_id
30   belongs_to :recipient, :class_name => "User", :foreign_key => :to_user_id
31
32   validates :title, :presence => true, :utf8 => true, :length => 1..255
33   validates :body, :sent_on, :presence => true
34   validates :title, :body, :characters => true
35
36   scope :muted, -> { where(:muted => true) }
37
38   before_create :set_muted
39
40   def self.from_mail(mail, from, to)
41     if mail.multipart?
42       if mail.text_part
43         body = mail.text_part.decoded
44       elsif mail.html_part
45         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
46       end
47     elsif mail.text? && mail.sub_type == "html"
48       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
49     else
50       body = mail.decoded
51     end
52
53     Message.new(
54       :sender => from,
55       :recipient => to,
56       :sent_on => mail.date.new_offset(0),
57       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
58       :body => body,
59       :body_format => "text"
60     )
61   end
62
63   def body
64     RichText.new(self[:body_format], self[:body])
65   end
66
67   def notification_token
68     sha256 = Digest::SHA256.new
69     sha256 << Rails.application.key_generator.generate_key("openstreetmap/message")
70     sha256 << id.to_s
71     Base64.urlsafe_encode64(sha256.digest)[0, 8]
72   end
73
74   def notify_recipient?
75     !muted?
76   end
77
78   def unmute
79     update(:muted => false)
80   end
81
82   private
83
84   def set_muted
85     self.muted ||= UserMute.active?(:owner => recipient, :subject => sender)
86   end
87 end