Runs whenever a new announcement is created, or a request is approved and posted.

    obj: The Announcement object
166234
def announcement_posted_hook(request, obj):
    
    logger.debug("Announcement posted")

    if obj.notify_post:
        logger.debug("Announcement notify on")
        announcement_posted_twitter(request, obj)
        try:
            notify_all = obj.notify_email_all
        except AttributeError:
            notify_all = False

        try:
            if notify_all:
                announcement_posted_email(request, obj, True)
            else:
                announcement_posted_email(request, obj)
        except Exception as e:
            logger.error("Exception when emailing announcement: {}".format(e))
            messages.error(request, "Exception when emailing announcement: {}".format(e))
            raise e
    else:
        logger.debug("Announcement notify off")
301091
async def announce(self):
        
        # send a serialized event
        await self.event_broker.send(
            action_type=intialize_service_action(),
            payload=json.dumps(self.summarize())
        )
427731
function (status) {
                if  (anouncementIds.length > 0 && anouncementIds.indexOf(that.getCurrentPlaylistId()) < 0)
                {
                  //The item after the announcement has starting buffering -> restore original volume if required
                  if (urlOptions && urlOptions.volume) {
                    that._client.setVolumePromise(currentVolume);
                    urlOptions = undefined; //So we not set it again on every status update
                  }

                  if (that.getStatus().playerState != "BUFFERING") {
                    //The item after the announcement has starting playing -> remove announcement from list
                    log.info ("%s - Resumed after announcement", that._name);
                    that.removeFromPlaylistPromise(anouncementIds);
                    anouncementIds = [];
                    //Anouncement ended
                    return resolve(url);
                  }

                }

                if
                (
                  anouncementIds.length === 0 /*Already completed announcement*/ &&
                  (
                    //Did we insert a chunk?
                    chunkItemIds.length === 0 ||
                    //Next item started playing ?
                    (nextItem && that.getCurrentPlaylistId() == nextItem.itemId && that.getStatus().playerState != "BUFFERING")
                  )
                )
                {
                  //The remaining current item we just inserted has starting playing -> remove
                  log.info ("%s - Back to regular playlist", that._name);
                  if (chunkItemIds.length > 0)
                    that.removeFromPlaylistPromise(chunkItemIds);

                  //We are done
                  that.removeListener(that.EVENT_STATUS, resumeAfterAnnouncement);
                  return;
                }

                //Sanity check - if all items disapear then this means that a new playlist was loaded
                let idsToCheck=anouncementIds.concat(chunkItemIds);
                let allGone = true;

                for (let i in idsToCheck) {
                  if (that._playlist.getItemWithId(idsToCheck[i]) != undefined)
                    allGone = false;
                    break;
                }
                if (allGone) {
                  log.warn("%s - remaining item to play after announcement not found in the playlist -> remove status handled", that._name);
                  that.removeListener(that.EVENT_STATUS, resumeAfterAnnouncement);
                  log.debug("%s - Player status:\n%s",that._name, util.inspect(that._status,{depth:null, colors:true}))
                }

                //Not the status update we are waiting for
              }
619943
function notify () {
  debug('run checker')
  debug(`ELINT_DISABLE_UPDATE_NOTIFIER: ${process.env.ELINT_DISABLE_UPDATE_NOTIFIER}`)

  if (process.env.ELINT_DISABLE_UPDATE_NOTIFIER === 'true') {
    return Promise.resolve(null)
  }

  return checker().then(result => {
    if (!result || !result.name || !result.latest || !result.current) {
      return null
    }

    conf.update(result.name)

    return report(result)
  })
}
391995
public synchronized void postNotification(final String name, Object... args) {
		postNotification(name, ObjectUtils.toMap(args));
	}
919947
def announce(self, msg):
        
        self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__))
        self.__trigger_event__(
            event_class=self.MessageAnnounced,
            msg=msg,
        )
494429
function notifyRetroactively(object) {
  if (object && typeof object === 'object') {
    const type = 'add';
    var notifier = Object.getNotifier(object);
    keys(object).forEach(name => notifier.notify({type, name, object}));
  }
  return object;
}
888699
function notifyIsolated(self,cb,chain) {
		var ret, _then;
		try {
			if (cb === false) {
				chain.reject(self.msg);
			}
			else {
				if (cb === true) {
					ret = self.msg;
				}
				else {
					ret = cb.call(void 0,self.msg);
				}

				if (ret === chain.promise) {
					chain.reject(TypeError("Promise-chain cycle"));
				}
				else if (_then = isThenable(ret)) {
					_then.call(ret,chain.resolve,chain.reject);
				}
				else {
					chain.resolve(ret);
				}
			}
		}
		catch (err) {
			chain.reject(err);
		}
	}
386026
def add_announcement_view(request):
    """"""
    if request.method == "POST":
        form = AnnouncementForm(request.POST)
        logger.debug(form)
        if form.is_valid():
            obj = form.save()
            obj.user = request.user
            # SAFE HTML
            obj.content = safe_html(obj.content)
            obj.save()
            announcement_posted_hook(request, obj)
            messages.success(request, "Successfully added announcement.")
            return redirect("index")
        else:
            messages.error(request, "Error adding announcement")
    else:
        form = AnnouncementForm()
    return render(request, "announcements/add_modify.html", {"form": form, "action": "add"})
860522
def get_is_notification(self, obj):
        
        try:
            o = compat_serializer_attr(self, obj)
            return o.is_notification
        except Exception:
            return False
764225
def open_notified_class
      class_eval do
        prepend NotificationActions
        attr_accessor :message, :notify_flag

        # Define association for the notified model
        has_many :notifications, class_name: 'SimpleNotifications::Record', as: :entity
        has_many :notifiers, through: :notifications, source: :sender, source_type: sender_class(@@options[:sender]).to_s
        has_many :read_deliveries, through: :notifications, source: :read_deliveries
        has_many :unread_deliveries, through: :notifications, source: :unread_deliveries

        # Callbacks
        after_create_commit :create_notification, if: proc {@@options[:callbacks].include?(:create)}
        after_update_commit :update_notification, if: proc {@@options[:callbacks].include?(:update)}
        after_destroy_commit :destroy_notification, if: proc {@@options[:callbacks].include?(:destroy)}

        NotificationActions.module_eval do
          @@options[:actions].each do |action|
            define_method(action) do
              run_callbacks action do
                super()
              end
            end

            define_method("before_#{action}".to_sym) do
            end

            define_method("after_#{action}".to_sym) do
              self.notify(sender: @@options[:sender], receivers: @@options[:receivers], message: default_message(self, @@options[:sender], action.to_s))
            end
          end
        end

        @@options[:actions].each do |action|
          define_model_callbacks action
          send("before_#{action}", "before_#{action}".to_sym)
          send("after_#{action}", "after_#{action}".to_sym)
        end

        #Example
        #post.notify(sender: :author, receivers: :followers, message: 'My Custom logic message')
        #post.create(content: '', notify: false) -> It does not create the notification.
        def notify(options = {})
          options[:sender] ||= @@options[:sender]
          options[:receivers] ||= @@options[:receivers]
          if notify_flag.nil? || (!notify_flag.nil? && !!notify_flag)
            raise 'SimpleNotification::SenderReceiverError' unless @@options[:sender] && @@options[:receivers]
            @message = options[:message] if options[:message]
            notification = notifications.build(entity: self, sender: get_obj(options[:sender]), message: default_message(self, get_obj(options[:sender]), 'created'))
            get_obj(options[:receivers]).each {|receiver| notification.deliveries.build(receiver: receiver)}
            notification.save
          end
        end

        def flush_notifications
          notifications.destroy_all
        end

        # Check if notifications has already been delivered.
        def notified?
          !notifications.blank?
        end

        def notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .collect(&:receiver)
        end

        def read_marked_notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .select{|record| record.is_read}
              .collect(&:receiver)
        end

        def unread_marked_notificants
          SimpleNotifications::Record.includes(deliveries: :receiver)
              .collect(&:deliveries).flatten
              .select{|record| !record.is_read}.collect(&:receiver)
        end

        # Mark notifications in read mode.
        # If notificants are provided then only those respective notifications will be marked read.
        # Else all will be marked as read.
        def mark_read(notificants = nil)
          (notificants ? unread_deliveries.where(receiver: notificants) : unread_deliveries).update_all(is_read: true)
        end

        # Mark notifications in unread mode.
        # If notificants are provided then only those respective notifications will be marked unread.
        # Else all will be marked as unread.
        def mark_unread(notificants = nil)
          (notificants ? read_deliveries.where(receiver: notificants) : read_deliveries).update_all(is_read: false)
        end

        def default_message(entity, sender, action)
          @message || (method(@@options[:notify_message]).call if !!@@options[:notify_message]) || "#{get_obj(sender).class.name} #{action} #{entity.class.name} #{entity.name}."
        end

        private

        def get_obj(sender_or_receivers)
          sender_or_receivers.kind_of?(Symbol) ? send(sender_or_receivers) : sender_or_receivers
        end

        def create_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'created')})
        end

        def update_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'updated')})
        end

        def destroy_notification
          notify({sender: get_obj(@@options[:sender]), receivers: get_obj(@@options[:receivers]), message: default_message(self, get_obj(@@options[:sender]), 'deleted')})
        end
      end
    end
546904
private void onMessageDelivered(MessageDeliveredEvent event) {
        handler.post(() -> listener.onMessageDelivered(event));
        log("Event published " + event.toString());
    }
1256853
def notify_handler(verb, **kwargs):
    

    # Pull the options out of kwargs
    kwargs.pop('signal', None)
    recipient = kwargs.pop('recipient')
    actor = kwargs.pop('sender')
    optional_objs = [
        (kwargs.pop(opt, None), opt)
        for opt in ('target', 'action_object')
    ]
    public = bool(kwargs.pop('public', True))
    description = kwargs.pop('description', None)
    timestamp = kwargs.pop('timestamp', timezone.now())
    level = kwargs.pop('level', Notification.LEVELS.info)

    # Check if User or Group
    if isinstance(recipient, Group):
        recipients = recipient.user_set.all()
    elif isinstance(recipient, (QuerySet, list)):
        recipients = recipient
    else:
        recipients = [recipient]

    new_notifications = []

    for recipient in recipients:
        newnotify = Notification(
            recipient=recipient,
            actor_content_type=ContentType.objects.get_for_model(actor),
            actor_object_id=actor.pk,
            verb=text_type(verb),
            public=public,
            description=description,
            timestamp=timestamp,
            level=level,
        )

        # Set optional objects
        for obj, opt in optional_objs:
            if obj is not None:
                setattr(newnotify, '%s_object_id' % opt, obj.pk)
                setattr(newnotify, '%s_content_type' % opt,
                        ContentType.objects.get_for_model(obj))

        if kwargs and EXTRA_DATA:
            newnotify.data = kwargs

        newnotify.save()
        new_notifications.append(newnotify)

    return new_notifications
95668
def run(self, request_cb, notification_cb):
        
        self._request_cb = request_cb
        self._notification_cb = notification_cb
        self._msgpack_stream.run(self._on_message)
        self._request_cb = None
        self._notification_cb = None
1035372
def admin_approve_announcement_view(request, req_id):
    
    req = get_object_or_404(AnnouncementRequest, id=req_id)

    requested_teachers = req.teachers_requested.all()
    logger.debug(requested_teachers)

    if request.method == "POST":
        form = AnnouncementRequestForm(request.POST, instance=req)
        if form.is_valid():
            req = form.save(commit=True)
            # SAFE HTML
            req.content = safe_html(req.content)
            if "approve" in request.POST:
                groups = []
                if "groups" in request.POST:
                    group_ids = request.POST.getlist("groups")
                    groups = Group.objects.filter(id__in=group_ids)
                logger.debug(groups)
                announcement = Announcement.objects.create(title=req.title, content=req.content, author=req.author, user=req.user,
                                                           expiration_date=req.expiration_date)
                for g in groups:
                    announcement.groups.add(g)
                announcement.save()

                req.posted = announcement
                req.posted_by = request.user
                req.save()

                announcement_approved_hook(request, announcement, req)
                announcement_posted_hook(request, announcement)

                messages.success(request, "Successfully approved announcement request. It has been posted.")
            else:
                req.rejected = True
                req.rejected_by = request.user
                req.save()
                messages.success(request, "You did not approve this request. It will be hidden.")
            return redirect("index")

    form = AnnouncementRequestForm(instance=req)
    all_groups = Group.objects.all()
    context = {"form": form, "req": req, "admin_approve": True, "all_groups": all_groups}
    return render(request, "announcements/approve.html", context)
158688
async def _on_headline(self, update):
        """"""

        name = update['service']
        message_obj = update['payload']
        new_headline = False

        if name not in self.services:
            return

        with self._state_lock:
            self.services[name].set_headline(message_obj['level'], message_obj['message'])

            if self.services[name].headline.count == 1:
                new_headline = True

        # Notify about this service state change if anyone is listening
        # headline changes are only reported if they are not duplicates
        if self._on_change_callback and new_headline:
            self._on_change_callback(name, self.services[name].id, self.services[name].state, False, True)
640231
def emit(self, action, event):
        
        NotificationManager.instance().emit(action, event, project_id=self.id)