notification.rb 1.99 KB
Newer Older
danielgrippi's avatar
danielgrippi committed
1
#   Copyright (c) 2010-2011, Diaspora Inc.  This file is
2 3
#   licensed under the Affero General Public License version 3 or later.  See
#   the COPYRIGHT file.
4
#
5
class Notification < ActiveRecord::Base
6 7 8 9
  belongs_to :recipient, class_name: "User"
  has_many :notification_actors, dependent: :destroy
  has_many :actors, class_name: "Person", through: :notification_actors, source: :person
  belongs_to :target, polymorphic: true
10

Raphael's avatar
Raphael committed
11
  def self.for(recipient, opts={})
12
    where(opts.merge!(recipient_id: recipient.id)).order("updated_at DESC")
13
  end
maxwell's avatar
maxwell committed
14

zhitomirskiyi's avatar
zhitomirskiyi committed
15
  def email_the_user(target, actor)
16
    recipient.mail(mail_job, recipient_id, actor.id, target.id)
17
  end
18

19
  def set_read_state( read_state )
20
    update_column(:unread, !read_state)
21
  end
22

23
  def mail_job
24
    raise NotImplementedError.new("Subclass this.")
25
  end
26

27 28
  def linked_object
    target
29 30
  end

31
  def self.concatenate_or_create(recipient, target, actor)
32
    return nil if suppress_notification?(recipient, actor)
33 34 35 36 37 38 39 40 41 42 43 44

    find_or_initialize_by(recipient: recipient, target: target, unread: true).tap do |notification|
      notification.actors |= [actor]
      # Explicitly touch the notification to update updated_at whenever new actor is inserted in notification.
      if notification.new_record? || notification.changed?
        notification.save!
      else
        notification.touch
      end
    end
  end

45 46 47 48
  def self.create_notification(recipient, target, actor)
    return nil if suppress_notification?(recipient, actor)

    create(recipient: recipient, target: target, actors: [actor])
49 50
  end

51 52
  private_class_method def self.suppress_notification?(recipient, actor)
    recipient.blocks.where(person: actor).exists?
53
  end
54 55 56 57 58 59 60 61 62 63 64

  def self.types
    {
      "also_commented" => "Notifications::AlsoCommented",
      "comment_on_post" => "Notifications::CommentOnPost",
      "liked" => "Notifications::Liked",
      "mentioned" => "Notifications::Mentioned",
      "reshared" => "Notifications::Reshared",
      "started_sharing" => "Notifications::StartedSharing"
    }
  end
65
end