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