~whereswaldon/sprig

ref: c852c94ed613f3c85024ce82e74269b185996c1a sprig/notifications.go -rw-r--r-- 2.0 KiB
c852c94eChris Waldon bugfix: do not notify for conversations created by local user a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main

import (
	"fmt"
	"log"

	forest "git.sr.ht/~whereswaldon/forest-go"
	"git.sr.ht/~whereswaldon/niotify"
)

type NotificationManager struct {
	*AppState
	niotify.Manager
}

func NewNotificationManager(state *AppState) (*NotificationManager, error) {
	mgr, err := niotify.NewManager()
	if err != nil {
		return nil, err
	}

	return &NotificationManager{
		AppState: state,
		Manager:  mgr,
	}, nil
}

func (n *NotificationManager) ShouldNotify(reply *forest.Reply) bool {
	if !n.AppState.NotificationsGloballyAllowed() {
		return false
	}
	if uint64(reply.Created) < n.AppState.TimeLaunched {
		// do not send old notifications
		return false
	}
	if n.AppState.Settings.ActiveIdentity == nil {
		return false
	}
	if reply.Author.Equals(n.AppState.Settings.ActiveIdentity) {
		// Do not send notifications for replies created by the local
		// user's identity.
		return false
	}
	if reply.TreeDepth() == 1 {
		// Notify of new conversation
		return true
	}
	parent, known, err := n.AppState.ArborState.SubscribableStore.Get(reply.ParentID())
	if err != nil || !known {
		// Don't notify if we don't know about this conversation.
		return false
	}
	if parent.(*forest.Reply).Author.Equals(n.AppState.Settings.ActiveIdentity) {
		// Direct response to local user.
		return true
	}
	return false
}

func (n *NotificationManager) HandleNode(node forest.Node) {
	if asReply, ok := node.(*forest.Reply); ok {
		go func(reply *forest.Reply) {
			if !n.ShouldNotify(reply) {
				return
			}
			var title, authorName string
			author, _, err := n.AppState.SubscribableStore.GetIdentity(&reply.Author)
			if err != nil {
				authorName = "???"
			} else {
				authorName = string(author.(*forest.Identity).Name.Blob)
			}
			switch {
			case reply.Depth == 1:
				title = fmt.Sprintf("New conversation by %s", authorName)
			default:
				title = fmt.Sprintf("New reply from %s", authorName)
			}
			_, err = n.Manager.CreateNotification(title, string(reply.Content.Blob))
			if err != nil {
				log.Printf("failed sending notification: %v", err)
			}
		}(asReply)
	}
}