-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbackground.js
170 lines (156 loc) · 5.15 KB
/
background.js
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
var enabled = false
var requestUrl = ""
var query = ""
var timeInterval = 30000
var popupData = {}
var latestAlertDate
var OPSGENIE_API = "https://api.opsgenie.com/"
var OPSGENIE_API_EU = "https://api.eu.opsgenie.com/"
var executeWithInterval
// start
setBadge(-1)
startExecution()
chrome.storage.onChanged.addListener(function (changes, namespace) {
startExecution()
});
chrome.runtime.onInstalled.addListener(details => {
window.open("options.html", "_blank")
});
// for communicating with popup view
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
sendResponse(popupData)
});
// overwriting the user agent
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name === "User-Agent") {
details.requestHeaders[i].value = "opsgenie-alert-notifier-extension"
break;
}
}
return {requestHeaders: details.requestHeaders};
},
{urls: ["*://*.opsgenie.com/*"]},
["blocking", "requestHeaders"]);
function startExecution() {
chrome.storage.sync.get({
region: 'US',
apiKey: '',
query: '',
enabled: true,
timeInterval: 30
}, function (items) {
clearTimeout(executeWithInterval)
var url = OPSGENIE_API
if (items.region === 'EU') {
url = OPSGENIE_API_EU
}
enabled = items.enabled
timeInterval = items.timeInterval * 1000
query = items.query
if (items.apiKey !== '') {
requestUrl = url + "v2/alerts?limit=100&sort=createdAt&" + "apiKey=" + items.apiKey + "&query=" + encodeURI(items.query)
}
doExecute()
})
}
function doExecute() {
if (requestUrl === "") {
setFailurePopupData("Notifier is not configured, please configure your extension in <a href=\"options.html\" target=\"_blank\"> option page↗</a>.")
return
}
if (!enabled) {
setBadge(-1)
setFailurePopupData("Alert API Poller is disabled, for enabling it use switch in <a href=\"options.html\" target=\"_blank\"> option page↗</a>.")
return
}
fetch(requestUrl)
.then(function (response) {
if (!response.ok) {
response.text().then(function (responseBody) {
setBadge(-1)
setFailurePopupData("Client failure, will retry in " + timeInterval/1000 + " seconds.<br> Reason: " + responseBody)
executeWithInterval = setTimeout(doExecute, timeInterval)
})
} else {
response.json().then(function (responseBody) {
setBadge(responseBody.data.length)
setSuccessPopupData(responseBody.data)
sendNotificationIfNewAlerts(responseBody.data)
executeWithInterval = setTimeout(doExecute, timeInterval)
})
}
}).catch(function(error){
setBadge(-1)
setFailurePopupData("Network failure, will retry in " + timeInterval/1000 + " seconds.<br> Reason: " + error)
executeWithInterval = setTimeout(doExecute, timeInterval)
})
}
function sendNotificationIfNewAlerts(data) {
if (latestAlertDate !== undefined) {
var newAlerts = []
for (let i = 0; i < data.length; i++) {
if (latestAlertDate < data[i].createdAt)
newAlerts.push({
"title": data[i].message,
"message": "Priority: " + data[i].priority
})
}
if (newAlerts.length == 1) {
chrome.notifications.create(data[0].id, {
type: 'basic',
iconUrl: 'images/128x128.png',
title: newAlerts[0].title,
message: newAlerts[0].message,
}, function () { });
} else if (newAlerts.length > 0) {
chrome.notifications.create('alert-list', {
type: 'list',
iconUrl: 'images/128x128.png',
title: newAlerts.length.toString() + " new alert(s)!",
message: "",
items: newAlerts
}, function () { });
}
}
if (data.length > 0) {
latestAlertDate = data[0].createdAt
}
}
chrome.notifications.onClicked.addListener(function (notificationId) {
if (notificationId === 'alert-list') {
window.open("https://app.opsgenie.com/alert/list?query=" + encodeURI(query), '_blank')
} else {
window.open('https://opsg.in/a/i/' + notificationId, '_blank')
}
});
function setBadge(count) {
if (count > 0) {
// red badge with alert count
chrome.browserAction.setBadgeText({ text: count.toString() })
chrome.browserAction.setBadgeBackgroundColor({ color: '#DE350B' }) // red
} else if (count < 0) {
// remove badge, no response alert api yet
chrome.browserAction.setBadgeText({ text: '' })
} else {
// empty green badge
chrome.browserAction.setBadgeBackgroundColor({ color: '#00875A' })
chrome.browserAction.setBadgeText({ text: ' ' })
}
}
function setSuccessPopupData(responseData) {
popupData.status = "success"
popupData.reason = ""
popupData.data = responseData
popupData.time = new Date().toLocaleString()
popupData.ogUrl = "https://app.opsgenie.com/alert/list?query=" + encodeURI(query)
}
function setFailurePopupData(message) {
popupData.status = "failure"
popupData.reason = message
popupData.data = []
popupData.time = new Date().toLocaleString()
popupData.ogUrl = "https://app.opsgenie.com/alert/list?query=" + encodeURI(query)
}