/
main.go
97 lines (85 loc) · 2.33 KB
/
main.go
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
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"context"
"fmt"
"os"
"os/exec"
"time"
"github.com/google/go-github/v41/github"
"golang.org/x/oauth2"
)
func main() {
token := os.Getenv("GH_TOKEN")
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
for notification := range notifications(ctx, client) {
if notification.Unread != nil && *notification.Unread {
popUp(notification)
}
}
}
func popUp(notification *github.Notification) {
text := "UNKNOWN"
if notification.Subject != nil && notification.Subject.Title != nil {
text = *notification.Subject.Title
}
subtitle := "UNKNOWN"
if notification.Subject != nil && notification.Subject.Type != nil {
subtitle = *notification.Subject.Type
}
if notification.Reason != nil {
subtitle += " / " + *notification.Reason
}
title := "Github"
if notification.Repository.Name != nil {
title = *notification.Repository.Name
}
sound := "Glass"
if notification.Subject != nil && notification.Subject.LatestCommentURL != nil {
fmt.Printf("\nURL: %s\n", *notification.Subject.LatestCommentURL)
}
script := fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\" sound name \"%s\"", text, title, subtitle, sound)
output, err := exec.Command("osascript", "-e", script).CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Could not send notification: %v\n", err)
}
if len(output) > 0 {
fmt.Printf("Notification Log: %s\n%s\n", script, output)
}
}
func notifications(ctx context.Context, client *github.Client) chan *github.Notification {
channel := make(chan *github.Notification)
ticker := time.NewTicker(time.Minute)
go func() {
defer ticker.Stop()
since := time.Now().AddDate(0, 0, -7) // week ago
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
objects, _, err := client.Activity.ListNotifications(ctx, &github.NotificationListOptions{
Since: since,
})
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting gh notifications %v\n", err)
}
for _, object := range objects {
if object.UpdatedAt != nil {
if since.Before(*object.UpdatedAt) {
since = *object.UpdatedAt
} else if *object.UpdatedAt == since {
continue
}
}
channel <- object
}
}
}
}()
return channel
}