notification.rb 2.12 KB
Newer Older
maxwell's avatar
maxwell committed
1 2 3 4
#   Copyright (c) 2010, Diaspora Inc.  This file is
#   licensed under the Affero General Public License version 3 or later.  See
#   the COPYRIGHT file.
#
5
class Notification < ActiveRecord::Base
6
  require File.join(Rails.root, 'lib/diaspora/web_socket')
Raphael's avatar
Raphael committed
7
  include Diaspora::Socketable
maxwell's avatar
maxwell committed
8

Raphael's avatar
Raphael committed
9
  belongs_to :recipient, :class_name => 'User'
Raphael Sofaer's avatar
Raphael Sofaer committed
10
  has_many :notification_actors
zhitomirskiyi's avatar
wip  
zhitomirskiyi committed
11
  has_many :actors, :class_name => 'Person', :through => :notification_actors, :source => :person
12
  belongs_to :target, :polymorphic => true
maxwell's avatar
maxwell committed
13

Raphael's avatar
Raphael committed
14
  def self.for(recipient, opts={})
15
    self.where(opts.merge!(:recipient_id => recipient.id)).order('updated_at desc')
maxwell's avatar
maxwell committed
16
  end
maxwell's avatar
maxwell committed
17

Raphael's avatar
Raphael committed
18
  def self.notify(recipient, target, actor)
19
    if target.respond_to? :notification_type
20
      if note_type = target.notification_type(recipient, actor)
21
        if target.is_a? Comment
22
          n = note_type.concatenate_or_create(recipient, target.post, actor, note_type)
23
        else
24
          n = note_type.make_notification(recipient, target, actor, note_type)
25
        end
26 27
        n.email_the_user(target, actor) if n
        n.socket_to_user(recipient, :actor => actor) if n
Raphael's avatar
Raphael committed
28
        n
maxwell's avatar
maxwell committed
29 30 31
       end
    end
  end
32

zhitomirskiyi's avatar
wip  
zhitomirskiyi committed
33
  def email_the_user(target, actor)
34
    self.recipient.mail(self.mail_job, self.recipient_id, actor.id, target.id)
35
  end
36 37 38
  def mail_job
    raise NotImplementedError.new('Subclass this.')
  end
39 40

private
41 42
  def self.concatenate_or_create(recipient, target, actor, notification_type)
    if n = notification_type.where(:target_id => target.id,
43
                              :target_type => target.class.base_class,
44 45
                               :recipient_id => recipient.id,
                               :unread => true).first
46 47 48
      unless n.actors.include?(actor)
        n.actors << actor
      end
49

50 51
      n.unread = true
      n.save!
52 53
      n
    else
54
      make_notification(recipient, target, actor, notification_type)
55 56 57
    end
  end

58 59
  def self.make_notification(recipient, target, actor, notification_type)
    n = notification_type.new(:target => target,
60
                               :recipient_id => recipient.id)
61
    n.actors << actor
62
    n.unread = false if target.is_a? Request
63 64 65
    n.save!
    n
  end
maxwell's avatar
maxwell committed
66
end