1 # frozen_string_literal: true
 
   3 # == Schema Information
 
   7 #  id                :bigint           not null, primary key
 
   8 #  from_user_id      :bigint           not null
 
   9 #  title             :string           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
 
  21 #  messages_from_user_id_idx  (from_user_id)
 
  22 #  messages_to_user_id_idx    (to_user_id)
 
  26 #  messages_from_user_id_fkey  (from_user_id => users.id)
 
  27 #  messages_to_user_id_fkey    (to_user_id => users.id)
 
  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
 
  34   validates :title, :presence => true, :utf8 => true, :length => 1..255
 
  35   validates :body, :sent_on, :presence => true
 
  36   validates :title, :body, :characters => true
 
  38   scope :muted, -> { where(:muted => true) }
 
  40   before_create :set_muted
 
  42   def self.from_mail(mail, from, to)
 
  45         body = mail.text_part.decoded
 
  47         body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
 
  49     elsif mail.text? && mail.sub_type == "html"
 
  50       body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
 
  58       :sent_on => mail.date.new_offset(0),
 
  59       :title => mail.subject.sub(/\[OpenStreetMap\] */, ""),
 
  61       :body_format => "text"
 
  66     RichText.new(self[:body_format], self[:body])
 
  69   def notification_token
 
  70     sha256 = Digest::SHA256.new
 
  71     sha256 << Rails.application.key_generator.generate_key("openstreetmap/message")
 
  73     Base64.urlsafe_encode64(sha256.digest)[0, 8]
 
  81     update(:muted => false)
 
  87     self.muted ||= UserMute.active?(:owner => recipient, :subject => sender)