-
Notifications
You must be signed in to change notification settings - Fork 1
/
feed.go
222 lines (193 loc) · 6.47 KB
/
feed.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Package function generate a JSON feed from authenticated user notifications
// Check https://jsonfeed.org/version/1.1 for more details
// https://docs.github.com/en/rest/reference/activity#list-notifications-for-the-authenticated-user
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"sync"
"time"
"github.com/google/go-github/v32/github"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/text/language"
)
var githubClient *github.Client
var c *cache.Cache
// Check https://jsonfeed.org/version/1.1 for more details
type jsonFeed struct {
Version string `json:"version"`
Title string `json:"title"`
HomePageURL string `json:"home_page_url"`
FeedURL string `json:"feed_url"`
Description string `json:"description,omitempty"`
UserComment string `json:"user_comment,omitempty"`
NextURL string `json:"next_url,omitempty"`
Icon string `json:"icon,omitempty"`
Favicon string `json:"favicon,omitempty"`
Authors []author `json:"authors,omitempty"`
Language language.Tag `json:"language,omitempty"`
Expired bool `json:"expired,omitempty"`
Items []item `json:"items"`
}
type author struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Avatar string `json:"avatar,omitempty"`
}
type item struct {
ID string `json:"id"`
URL string `json:"url"`
Title string `json:"title"`
ContentHTML string `json:"content_html,omitempty"`
ContentText string `json:"content_text,omitempty"`
DatePublished string `json:"date_published,omitempty"`
DateModified string `json:"date_modified,omitempty"`
}
func init() {
// Set up cache for rate-limit request
// Create a cache with a default expiration time of 5 minutes, and which
// purges expired items every 10 minutes
c = cache.New(5*time.Minute, 10*time.Minute)
}
// Execute a custom HTTP request with Github client
func customGithubRequest(ctx context.Context, url string) (string, *github.Response, error) {
log.Debugf("URL being requested: %s\n", url)
req, err := githubClient.NewRequest("GET", url, nil)
if err != nil {
return "", nil, err
}
var result map[string]interface{}
resp, err := githubClient.Do(ctx, req, &result)
if err != nil {
return "", resp, err
}
// html_url is always a string
return result["html_url"].(string), nil, nil
}
func sendResponse(w http.ResponseWriter, feed *jsonFeed) {
data, _ := json.Marshal(feed)
w.Header().Set("Content-Type", "application/feed+json")
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%s", 5*time.Minute))
w.Write(data)
}
func getGithubNotificationsJSONFeed(w http.ResponseWriter, r *http.Request) {
log.Infoln("Read Github user token from request")
var githubToken string = r.URL.Query().Get("token")
if githubToken == "" {
log.Warningln("Token not found, aborting")
http.Error(w, "Forbidden", 403)
return
}
log.Debugln("Check if not already in cache")
var feed *jsonFeed
if x, found := c.Get(githubToken); found {
log.Infoln("Found in cache, send it!")
feed = x.(*jsonFeed)
// Send immediately
sendResponse(w, feed)
return
}
ctx := context.Background()
// Create Github client only if not exist yet
if githubClient == nil {
log.Debugln("Create Github client")
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
tc := oauth2.NewClient(ctx, ts)
// Store github client in memory for future calls
githubClient = github.NewClient(tc)
}
log.Debugln("List unread notifications")
notifications, resp, err := githubClient.Activity.ListNotifications(ctx, &github.NotificationListOptions{
// Get all notifications
All: true,
// Only 20 is sufficient
ListOptions: github.ListOptions{
PerPage: 20,
},
})
if err != nil {
log.Errorf("Error on notifications list: %s", err)
http.Error(w, resp.Status, resp.StatusCode)
return
}
// For each notifications, create a feed item
log.Infof("Found %d notifications\n", len(notifications))
var items []item = make([]item, 0)
var wg sync.WaitGroup
for _, notification := range notifications {
wg.Add(1)
go func(n *github.Notification) {
defer wg.Done()
// Create default title
t := fmt.Sprintf("[%s] %s - %s", n.GetSubject().GetType(), n.Repository.GetFullName(), n.Subject.GetTitle())
// Default Notification HTML URL to repo URL for private repo
// https://docs.github.com/en/free-pro-team@latest/rest/reference/pulls#get-a-pull-request
var htmlURL string = strings.Replace(n.Subject.GetURL(), "https://api.github.com/repos", "https://github.com", 1)
htmlURL = strings.Replace(htmlURL, "pulls", "pull", 1)
// Try to get the real URL in case of public repo
u, _, err := customGithubRequest(ctx, n.Subject.GetURL())
if err == nil {
// If not error, use this URL instead of the default one
htmlURL = u
} else {
// Use Github Error if provided
var m []string = []string{err.Error()}
if v, ok := err.(*github.ErrorResponse); ok {
for _, e := range v.Errors {
m = append(m, e.Message)
}
}
log.Errorf("Error on notifications list: %s", strings.Join(m, ", "))
}
items = append(items, item{
ID: n.GetID(),
URL: htmlURL,
Title: t,
ContentText: t,
DatePublished: n.GetUpdatedAt().Format(time.RFC3339),
})
}(notification)
}
log.Debugln("Waiting for process")
wg.Wait()
// Sort items by date
sort.Slice(items, func(i, j int) bool {
return items[i].DatePublished > items[j].DatePublished
})
feed = &jsonFeed{
Version: "https://jsonfeed.org/version/1.1",
Title: "Github Notifications",
HomePageURL: "https://github.com/notifications",
FeedURL: feedURL,
Description: "Your Github notifications",
Icon: "https://www.iconfinder.com/data/icons/octicons/1024/mark-github-512.png",
Favicon: "https://github.com/favicon.ico",
Authors: []author{
{
Name: "Quentin Lemaire",
Avatar: "https://gravatar.com/avatar/ae3ee0665731b1010ed57bd608ac213b?s=400&d=robohash&r=x",
URL: "https://lemairepro.fr",
},
{
Name: "Github",
Avatar: "https://www.iconfinder.com/data/icons/octicons/1024/mark-github-512.png",
URL: "https://github.com",
},
},
Language: language.AmericanEnglish,
Expired: false,
Items: items,
}
log.Infoln("Store in cache")
c.Set(githubToken, feed, cache.DefaultExpiration)
// Send final response
sendResponse(w, feed)
}