/* ----------------------- Notifications ------------------------*/
355869
func (mc MongoClient) GetNotifications() ([]contract.Notification, error) {
	return mc.getNotifications(bson.M{})
}
650372
func (m *wsNotificationManager) notificationHandler() {
	// clients is a map of all currently connected websocket clients.
	clients := make(map[chan struct{}]*wsClient)

	// Maps used to hold lists of websocket clients to be notified on
	// certain events.  Each websocket client also keeps maps for the events
	// which have multiple triggers to make removal from these lists on
	// connection close less horrendously expensive.
	//
	// Where possible, the quit channel is used as the unique id for a client
	// since it is quite a bit more efficient than using the entire struct.
	blockNotifications := make(map[chan struct{}]*wsClient)
	txNotifications := make(map[chan struct{}]*wsClient)
	watchedOutPoints := make(map[wire.OutPoint]map[chan struct{}]*wsClient)
	watchedAddrs := make(map[string]map[chan struct{}]*wsClient)

out:
	for {
		select {
		case n, ok := <-m.notificationMsgs:
			if !ok {
				// queueHandler quit.
				break out
			}
			switch n := n.(type) {
			case *notificationBlockConnected:
				block := (*btcutil.Block)(n)

				// Skip iterating through all txs if no
				// tx notification requests exist.
				if len(watchedOutPoints) != 0 || len(watchedAddrs) != 0 {
					for _, tx := range block.Transactions() {
						m.notifyForTx(watchedOutPoints,
							watchedAddrs, tx, block)
					}
				}

				if len(blockNotifications) != 0 {
					m.notifyBlockConnected(blockNotifications,
						block)
					m.notifyFilteredBlockConnected(blockNotifications,
						block)
				}

			case *notificationBlockDisconnected:
				block := (*btcutil.Block)(n)

				if len(blockNotifications) != 0 {
					m.notifyBlockDisconnected(blockNotifications,
						block)
					m.notifyFilteredBlockDisconnected(blockNotifications,
						block)
				}

			case *notificationTxAcceptedByMempool:
				if n.isNew && len(txNotifications) != 0 {
					m.notifyForNewTx(txNotifications, n.tx)
				}
				m.notifyForTx(watchedOutPoints, watchedAddrs, n.tx, nil)
				m.notifyRelevantTxAccepted(n.tx, clients)

			case *notificationRegisterBlocks:
				wsc := (*wsClient)(n)
				blockNotifications[wsc.quit] = wsc

			case *notificationUnregisterBlocks:
				wsc := (*wsClient)(n)
				delete(blockNotifications, wsc.quit)

			case *notificationRegisterClient:
				wsc := (*wsClient)(n)
				clients[wsc.quit] = wsc

			case *notificationUnregisterClient:
				wsc := (*wsClient)(n)
				// Remove any requests made by the client as well as
				// the client itself.
				delete(blockNotifications, wsc.quit)
				delete(txNotifications, wsc.quit)
				for k := range wsc.spentRequests {
					op := k
					m.removeSpentRequest(watchedOutPoints, wsc, &op)
				}
				for addr := range wsc.addrRequests {
					m.removeAddrRequest(watchedAddrs, wsc, addr)
				}
				delete(clients, wsc.quit)

			case *notificationRegisterSpent:
				m.addSpentRequests(watchedOutPoints, n.wsc, n.ops)

			case *notificationUnregisterSpent:
				m.removeSpentRequest(watchedOutPoints, n.wsc, n.op)

			case *notificationRegisterAddr:
				m.addAddrRequests(watchedAddrs, n.wsc, n.addrs)

			case *notificationUnregisterAddr:
				m.removeAddrRequest(watchedAddrs, n.wsc, n.addr)

			case *notificationRegisterNewMempoolTxs:
				wsc := (*wsClient)(n)
				txNotifications[wsc.quit] = wsc

			case *notificationUnregisterNewMempoolTxs:
				wsc := (*wsClient)(n)
				delete(txNotifications, wsc.quit)

			default:
				rpcsLog.Warn("Unhandled notification type")
			}

		case m.numClients <- len(clients):

		case <-m.quit:
			// RPC server shutting down.
			break out
		}
	}

	for _, c := range clients {
		c.Disconnect()
	}
	m.wg.Done()
}
1201917
func (s *UpdateClusterInput) SetNotification(v *Notification) *UpdateClusterInput {
	s.Notification = v
	return s
}
645275
func Alert(appName string, title string, text string, iconPath string) {
	note := notification(appName, title, text, iconPath)
	note.Audio = toast.Default
	if err := note.Push(); err != nil {
		log.Println("ERROR:", err)
	}
}
781569
func (s *SubscriptionProvider) Notify(event interface{}) {
	s.RLock()
	defer s.RUnlock()
	for _, sub := range s.subscriptions {
		if err := sub.notify(event); err != nil {
			Log.Warnf("Failed notifying subscription (%s): %s", sub.id, err)
		}
	}
}
915220
func (notifier *HipChatNotifier) Notify(messages Messages) bool {

	overallStatus, pass, warn, fail := messages.Summary()

	text := fmt.Sprintf("%s is <STRONG>%s</STRONG>. Fail: %d, Warn: %d, Pass: %d", notifier.ClusterName, overallStatus, fail, warn, pass)

	for _, message := range messages {
		text += fmt.Sprintf("<BR><STRONG><CODE>%s</CODE></STRONG>:%s:%s is <STRONG>%s</STRONG>.",
			message.Node, html.EscapeString(message.Service), html.EscapeString(message.Check), message.Status)
		if utf8.RuneCountInString(message.Output) > 0 {
			text += fmt.Sprintf("<BR>%s", strings.Replace(html.EscapeString(strings.TrimSpace(message.Output)), "\n", "<BR>", -1))
		}
	}

	level := "green"
	if fail > 0 {
		level = "red"
	} else if warn > 0 {
		level = "yellow"
	}

	client := hipchat.NewClient(notifier.AuthToken)
	if notifier.BaseURL != "" {
		url, err := url.Parse(notifier.BaseURL)
		if err != nil {
			log.Printf("Error parsing hipchat base url: %s\n", err)
		}
		client.BaseURL = url
	}

	from := ""
	if notifier.From != "" {
		from = notifier.From
	}

	notifRq := &hipchat.NotificationRequest{
		Color:         level,
		Message:       text,
		Notify:        true,
		MessageFormat: "html",
		From:          from,
	}

	resp, err := client.Room.Notification(notifier.RoomId, notifRq)

	if err != nil {
		log.Printf("Error sending notification to hipchat: %s\n", err)
		log.Printf("Server returns %+v\n", resp)
		return false
	}

	return true
}
680561
func (s *Swarm) Notify(f inet.Notifiee) {
	s.notifs.Lock()
	s.notifs.m[f] = struct{}{}
	s.notifs.Unlock()
}
342459
func NewNotification(summary, body string) Notification {
	return Notification{
		Summary: summary,
		Body:    body,
		Timeout: ExpiresDefault,
	}
}
656781
func SendNotification(msg PushNotification) {
	switch msg.Platform {
	case PlatFormIos:
		PushToIOS(msg)
	case PlatFormAndroid:
		PushToAndroid(msg)
	}
}
422298
func (a *API) GetNotification(user int, id int) (*Notification, error) {
	dst := new(Notification)
	url := a.BuildURL("/v2/user/%d/notification/%d", user, id)
	err := a.Get(url, Params{}, dst)
	return dst, err
}
755707
func (a *API) FindNotifications(user int, filter string) ([]Notification, error) {
	params := Params{}
	if filter != EmptyFilter {
		params["q"] = filter
	}

	dst := make([]Notification, 0)
	url := a.BuildURL("/v2/user/%d/notification", user)
	err := a.Get(url, params, &dst)
	return dst, err
}
871598
func (s *NotificationServer) AccountNotifications() AccountNotificationsClient {
	c := make(chan *AccountNotification)
	s.mu.Lock()
	s.accountClients = append(s.accountClients, c)
	s.mu.Unlock()
	return AccountNotificationsClient{
		C:      c,
		server: s,
	}
}
397806
func (n *Notifier) Notify(eventType EventType, message string, increment bool) {
	notif := &notification{
		Type:      eventType,
		Message:   message,
		Increment: increment,
	}

	if increment {
		n.Lock()
		n.current++
		n.Unlock()
	}

	n.RLock()
	current := n.current
	total := n.total
	n.RUnlock()

	if current > total {
		panic(fmt.Sprintf(
			"notifications exceed maximum %d/%d", current, total))
	}

	select {
	case n.notifications <- notif:
		return
	case <-n.observerClosed:
		return
	case <-n.ctxDone:
		return
	}
}
720668
func (emailNotifier *EmailNotifier) Notify(alerts Messages) bool {

	overAllStatus, pass, warn, fail := alerts.Summary()
	nodeMap := mapByNodes(alerts)

	var emailDataList []TemplateData

	if emailNotifier.OnePerAlert {
		log.Println("Going to send one email per alert")
		emailDataList = []TemplateData{}
		for _, check := range alerts {

			singleAlertChecks := make(Messages, 0)
			singleAlertChecks = append(singleAlertChecks, check)
			singleAlertMap := mapByNodes(singleAlertChecks)

			alertStatus, alertPassing, alertWarnings, alertFailures := singleAlertChecks.Summary()

			alertClusterName := emailNotifier.ClusterName + " " + check.Node + " - " + check.CheckId

			e := TemplateData{
				ClusterName:  alertClusterName,
				SystemStatus: alertStatus,
				FailCount:    alertFailures,
				WarnCount:    alertWarnings,
				PassCount:    alertPassing,
				Nodes:        singleAlertMap,
			}
			emailDataList = append(emailDataList, e)
		}
	} else if emailNotifier.OnePerNode {
		log.Println("Going to send one email per node")
		emailDataList = []TemplateData{}
		for nodeName, checks := range nodeMap {
			singleNodeMap := mapByNodes(checks)
			nodeStatus, nodePassing, nodeWarnings, nodeFailures := checks.Summary()

			nodeClusterName := emailNotifier.ClusterName + " " + nodeName

			e := TemplateData{
				ClusterName:  nodeClusterName,
				SystemStatus: nodeStatus,
				FailCount:    nodeFailures,
				WarnCount:    nodeWarnings,
				PassCount:    nodePassing,
				Nodes:        singleNodeMap,
			}
			emailDataList = append(emailDataList, e)
		}
	} else {
		log.Println("Going to send one email for many alerts")
		e := TemplateData{
			ClusterName:  emailNotifier.ClusterName,
			SystemStatus: overAllStatus,
			FailCount:    fail,
			WarnCount:    warn,
			PassCount:    pass,
			Nodes:        nodeMap,
		}

		emailDataList = []TemplateData{e}
	}

	success := true

	for _, e := range emailDataList {

		var renderedTemplate string
		var err error
		renderedTemplate, err = renderTemplate(e, emailNotifier.Template, defaultTemplate)

		if err != nil {
			log.Println("Template error, unable to send email notification: ", err)
			success = false
			continue
		}

		msg := fmt.Sprintf(`From: "%s" <%s>
To: %s
Subject: %s is %s
MIME-version: 1.0;
Content-Type: text/html; charset="UTF-8";

%s
`,
			emailNotifier.SenderAlias,
			emailNotifier.SenderEmail,
			strings.Join(emailNotifier.Receivers, ", "),
			e.ClusterName,
			e.SystemStatus,
			renderedTemplate)

		addr := fmt.Sprintf("%s:%d", emailNotifier.Url, emailNotifier.Port)
		auth := smtp.PlainAuth("", emailNotifier.Username, emailNotifier.Password, emailNotifier.Url)
		if err := sendMail(addr, auth, emailNotifier.SenderEmail, emailNotifier.Receivers, []byte(msg)); err != nil {
			log.Println("Unable to send notification:", err)
			continue
		}
		log.Println("Email notification sent.")
		success = success && true
	}

	return success
}
727404
func (s *CreateClusterInput) SetNotification(v *Notification) *CreateClusterInput {
	s.Notification = v
	return s
}
795515
func (c Client) AddNotification(n contract.Notification) (string, error) {
	conn := c.Pool.Get()
	defer conn.Close()

	err := addNotification(conn, &n)
	if err != nil {
		return "", err
	}
	return n.ID, nil
}
237705
func (sys *NotificationSys) RemoveNotification(bucketName string) {
	sys.Lock()
	defer sys.Unlock()

	delete(sys.bucketRulesMap, bucketName)

	for targetID := range sys.bucketRemoteTargetRulesMap[bucketName] {
		sys.targetList.Remove(targetID)
		delete(sys.bucketRemoteTargetRulesMap[bucketName], targetID)
	}

	delete(sys.bucketRemoteTargetRulesMap, bucketName)
}