-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
416 lines (343 loc) · 14 KB
/
index.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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*!
* reviews-to-slack
* Copyright(c) 2018 Niklas Wahlén
* MIT Licensed
*/
const request = require('request')
const Watcher = require('rss-watcher')
const cheerio = require('cheerio')
const WATCHER_EVENTS = {
'NEW_ARTICLE': 'new article',
'ERROR': 'error'
}
const REVIEWS_STORES = {
'APP_STORE': 'app-store',
'GOOGLE_PLAY': 'google-play'
}
const REVIEWS_LIMIT = 50
const DEFAULT_INTERVAL_SECONDS = 300
var publishedReviews = [];
(function () {
exports.start = function start (config) {
if (!config.store) {
// Determine from which store reviews are downloaded
config.store = (config.appId.indexOf('.') > -1) ? REVIEWS_STORES.GOOGLE_PLAY : REVIEWS_STORES.APP_STORE
}
var appInformation = {}
if (config.store === REVIEWS_STORES.APP_STORE) {
if (!config.region) {
config.region = 'us'
}
if (!config.feed) {
config.feed = 'https://itunes.apple.com/' + config.region + '/rss/customerreviews/id=' + config.appId + '/sortBy=mostRecent/xml'
} else {
console.log('INFO: Setting feed directly is deprecated, see updated docs at https://github.com/wahni/reviews-to-slack')
}
var watcher = new Watcher(config.feed)
watcher.set({
feed: config.feed,
interval: config.interval != null ? config.interval : DEFAULT_INTERVAL_SECONDS
})
watcher.on(WATCHER_EVENTS.NEW_ARTICLE, function onNewArticle (item) {
if (!item) {
if (config.debug) console.log('WARNING: Received null or undefined review')
return
}
if (isAppStoreInformationEntry(item)) {
if (config.debug) console.log('INFO: Received new app information')
updateAppStoreAppInformation(config, item, appInformation)
return
}
var review = exports.parseAppStoreReview(item, config, appInformation)
if (!exports.reviewPublished(review)) {
if (config.debug) console.log('INFO: Received new review: ' + review)
var message = exports.slackMessage(review, config, appInformation)
exports.postToSlack(message, config)
exports.markReviewAsPublished(config, review)
} else if (exports.reviewPublished(config, review)) {
if (config.debug) console.log('INFO: Review already published: ' + review.text)
}
})
watcher.on(WATCHER_EVENTS.ERROR, function onError (error) {
return console.error('ERROR: for new review: ' + error)
})
return watcher.run(function run (error, entries) {
if (error != null) return console.error('ERROR: Could not parse feed for ' + config.appId + ', ' + error)
if (entries == null) return console.log('WARNING: Currently no reviews available for ' + config.appId)
// Parse existing entries for app information
for (var i = 0; i < entries.length; i++) {
var item = entries[i]
var review = exports.parseAppStoreReview(item, config, appInformation)
// Mark any eixsting reviews as published
exports.markReviewAsPublished(config, review)
updateAppStoreAppInformation(config, item, appInformation)
}
if (config.debug) {
console.log('INFO: Started watching app: ' + (config.appName ? config.appName : appInformation.appName))
var welcome = welcomeMessage(config, appInformation)
exports.postToSlack(welcome, config)
}
})
} else {
exports.setupGooglePlayAppInformation(config, appInformation, function () {
exports.fetchGooglePlayReviews(config, appInformation, function (initialReviews) {
for (var i = 0; i < initialReviews.length; i++) {
var initialReview = initialReviews[i]
exports.markReviewAsPublished(config, initialReview)
}
var intervalSeconds = config.interval ? config.interval : DEFAULT_INTERVAL_SECONDS
setInterval(function (config, appInformation) {
if (config.debug) console.log('INFO: [' + config.appId + '] Fetching Google Play reviews')
exports.fetchGooglePlayReviews(config, appInformation, function (reviews) {
exports.handleFetchedGooglePlayReviews(config, appInformation, reviews)
})
}, intervalSeconds * 1000, config, appInformation)
if (config.debug) {
console.log('INFO: [' + config.appId + '] Started watching app: ' + (config.appName ? config.appName : appInformation.appName))
var welcome = welcomeMessage(config, appInformation)
exports.postToSlack(welcome, config)
}
})
})
}
}
}).call(this)
// Google Play
exports.setupGooglePlayAppInformation = function (config, appInformation, callback) {
appInformation.appLink = 'https://play.google.com/store/apps/details?id=' + config.appId
if (config.region) {
appInformation.appLink += '&gl=' + config.region + '&hl=' + config.region
}
request.get(appInformation.appLink, function (error, response, body) {
if (error) {
console.error('WARNING: [' + config.appId + '] Could not fetch app information, ' + error)
} else if (body) {
const $ = cheerio.load(body)
appInformation.appName = $('[itemprop="name"]').text().trim()
if (config.debug) console.log('INFO: [' + config.appId + '] Fetched app name: ' + appInformation.appName)
var webpIcon = $('[itemprop="image"]').attr('src')
if (typeof webpIcon === 'string' && !webpIcon.startsWith('http')) {
webpIcon = 'https:' + webpIcon
}
appInformation.appIcon = webpIcon + '-no-tmp.png' // Force png as Slack currently cannot display the WebP image.
if (config.debug) console.log('INFO: [' + config.appId + '] Fetched app icon: ' + appInformation.appIcon)
}
callback()
})
}
exports.handleFetchedGooglePlayReviews = function (config, appInformation, reviews) {
for (var n = 0; n < reviews.length; n++) {
var review = reviews[n]
if (exports.reviewPublished(review)) {
continue
}
if (config.debug) console.log('INFO: [' + config.appId + '] Found a new Google Play review: ' + review.text)
var message = exports.slackMessage(review, config, appInformation)
exports.postToSlack(message, config)
exports.markReviewAsPublished(config, review)
}
}
exports.fetchGooglePlayReviews = function (config, appInformation, callback) {
var form = {'xhr': 1, 'id': config.appId, 'reviewSortOrder': 0, 'pageNum': 0, 'reviewType': 0}
if (config.region) {
form['gl'] = config.region
form['hl'] = config.region
}
request.post({
url: 'https://play.google.com/store/getreviews',
form: form
},
function (error, response, body) {
if (config.debug) console.log('INFO: [' + config.appId + '] Got response for request ' + JSON.stringify(response.request))
if (error) {
console.error('ERROR: [' + config.appId + '] Could not fetch Google Play reviews, ' + error)
} else {
// The body contains some unwanted prefix data, then a JSON matrix (starts with '[')
// The actual HTML body that contains the reviews is at position (0,2).
var bodyString = String(body)
var jsonBody = []
try {
jsonBody = JSON.parse(bodyString.substring(bodyString.indexOf('[')))
} catch (e) {
console.error('ERROR: [' + config.appId + '] Could not parse JSON in: ' + bodyString + ', ' + e)
callback(new Error([]))
return
}
var reviewsBody = jsonBody[0][2]
if (!reviewsBody) {
if (config.debug) console.log('INFO: [' + config.appId + '] No reviews in body: ' + bodyString)
callback(new Error([]))
return
}
try {
var $ = cheerio.load(reviewsBody)
} catch (e) {
console.error('ERROR: [' + config.appId + '] Could not parse HTML: ' + reviewsBody + ', ' + e)
callback(new Error([]))
return
}
var htmlReviews = $('.single-review')
var reviews = htmlReviews.map(function (i, element) {
// this === element
var review = {}
review.id = $(this).find('.review-header').attr('data-reviewid')
review.date = $(this).find('.review-header .review-date').text().trim()
review.title = $(this).find('.review-body .review-title').text().trim()
review.text = $(this).find('.review-body').first().contents().filter(function () {
return this.type === 'text'
}).text().trim()
review.author = $(this).find('.review-header .author-name').text().trim()
var ratingData = $(this).find('.current-rating').attr('style')
review.rating = parseInt(ratingData.replace(/[^\d]/g, '')) / 20
review.link = 'https://play.google.com' + $(this).find('.reviews-permalink').attr('href')
review.storeName = 'Google Play'
return review
})
callback(reviews)
}
}
)
}
// Published reviews
exports.markReviewAsPublished = function (config, review) {
if (!review || !review.id || this.reviewPublished(review)) return
if (publishedReviews.count >= REVIEWS_LIMIT) {
publishedReviews.pop(publishedReviews.count - (REVIEWS_LIMIT + 1))
}
publishedReviews.unshift(review.id)
}
exports.reviewPublished = function (review) {
if (!review || !review.id) return false
return publishedReviews.indexOf(review.id) >= 0
}
exports.publishedReviews = function () {
return publishedReviews
}
exports.resetPublishedReviews = function () {
publishedReviews = []
}
// App Store
var isAppStoreInformationEntry = function (entry) {
// App Store app information is available in an entry with some special fields
return entry != null && entry['im:name']
}
var updateAppStoreAppInformation = function (config, entry, appInformation) {
if (!isAppStoreInformationEntry(entry)) return
if (config.appName == null && entry['im:name'] != null) {
appInformation.appName = entry['im:name']['#']
if (config.debug) console.log('INFO: Found app name: ' + appInformation.appName)
}
if (config.appIcon == null && entry['im:image'] && entry['im:image'].length > 0) {
appInformation.appIcon = entry['im:image'][0]['#']
if (config.debug) console.log('INFO: Found app icon: ' + appInformation.appIcon)
}
if (config.appLink == null && entry['link']) {
appInformation.appLink = entry['link']
if (config.debug) console.log('INFO: Found app link: ' + appInformation.appLink)
}
}
exports.parseAppStoreReview = function (rssItem, config, appInformation) {
var review = {}
review.id = rssItem['id']
review.title = rssItem.title
review.text = rssItem.description
review.rating = reviewRating(rssItem, config)
review.date = reviewDate(rssItem, config)
review.author = rssItem.author
review.link = config.appLink ? config.appLink : appInformation.appLink
review.storeName = 'App Store'
return review
}
// Slack
exports.slackMessage = function (review, config, appInformation) {
if (config.debug) console.log('INFO: Creating message for review ' + review.title)
var stars = ''
for (var i = 0; i < 5; i++) {
stars += i < review.rating ? '★' : '☆'
}
var pretext = 'New review'
if (config.appName != null || appInformation.appName != null) {
pretext += ' for ' + (config.appName ? config.appName : appInformation.appName)
}
pretext += '!'
var color = review.rating >= 4 ? 'good' : (review.rating >= 2 ? 'warning' : 'danger')
var text = ''
text += review.text + '\n'
text += '_by ' + review.author
if (review.date) {
text += ', ' + review.date
}
if (review.link) {
text += ' - ' + '<' + review.link + '|' + review.storeName + '>'
} else {
text += ' - ' + review.storeName
}
text += '_'
var message = {
'username': config.botUsername,
'icon_url': config.botIcon,
'channel': config.channel,
'attachments': [
{
'mrkdwn_in': ['text', 'pretext', 'title'],
'fallback': pretext + ': ' + review.title + ' (' + stars + '): ' + review.text,
'pretext': pretext,
'color': color,
'author_name': stars,
'author_icon': config.appIcon ? config.appIcon : appInformation.appIcon,
'title': review.title,
'title_link': review.link,
'text': text
}
]
}
return message
}
var welcomeMessage = function (config, appInformation) {
var storeName = config.store === REVIEWS_STORES.APP_STORE ? 'App Store' : 'Google Play'
var appName = config.appName ? config.appName : (appInformation.appName ? appInformation.appName : config.appId)
return {
'username': config.botUsername,
'icon_url': config.botIcon,
'channel': config.channel,
'attachments': [
{
'mrkdwn_in': ['pretext', 'author_name'],
'fallback': 'This channel will now receive ' + storeName + ' reviews for ' + appName,
'pretext': 'This channel will now receive ' + storeName + ' reviews for ',
'author_name': appName,
'author_icon': config.appIcon ? config.appIcon : appInformation.appIcon
}
]
}
}
var reviewRating = function (review, config) {
if (config.store === REVIEWS_STORES.APP_STORE) {
return review['im:rating'] != null && !isNaN(review['im:rating']['#']) ? parseInt(review['im:rating']['#']) : -1
} else if (config.store === REVIEWS_STORES.GOOGLE_PLAY) {
var rating = review.title.substr(0, 1)
return rating != null && !isNaN(rating) ? parseInt(rating) : -1
} else {
return -1
}
}
var reviewDate = function (review, config) {
if (config.store === REVIEWS_STORES.APP_STORE) {
return review.date.toISOString().replace('T', ' ').substr(0, 16)
} else if (config.store === REVIEWS_STORES.GOOGLE_PLAY) {
return undefined // Google Play review RSS dates are often unreliable (current date instead of review date)
} else {
return undefined
}
}
exports.postToSlack = function (message, config) {
var messageJSON = JSON.stringify(message)
if (config.debug) console.log('INFO: Posting new message to Slack: ' + messageJSON)
return request.post({
url: config.slackHook,
headers: {
'Content-Type': 'application/json'
},
body: messageJSON
})
}