-
Notifications
You must be signed in to change notification settings - Fork 3
/
sentimentController.js
398 lines (331 loc) · 13.1 KB
/
sentimentController.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
const fetch = require("node-fetch");
const Sentiment = require("sentiment");
const sentiment = new Sentiment();
const { saveSentimentData, getExtraWords, saveExtraWords } = require("./firebaseController");
const { getSubreddit } = require("./redditController");
const { performStandardSearch, performPremiumSearch } = require("./twitterController");
const { searchNews } = require("./bingNewsController");
const { retry } = require("./retryController")
const { updateExtraWordCache, getExtraWordCache } = require("./cacheController")
const l = require("./logController");
const h = require("../helpers");
function _getTotals(arrayOfResults) {
let nonZeroResults = arrayOfResults.filter((result) => result.analysed.length > 0);
let cumulativeScoresOnly = nonZeroResults.map((result) => result.cumulativeScore);
let cumulativeComparativeOnly = nonZeroResults.map((result) => result.cumulativeComparative);
let totalCumulativeScore = cumulativeScoresOnly.reduce((a, b) => a + b);
let totalCumulativeComparative = cumulativeComparativeOnly.reduce((a, b) => a + b);
let averageScore = totalCumulativeScore / nonZeroResults.length;
let averageComparative = totalCumulativeComparative / nonZeroResults.length;
return { totalCumulativeScore, totalCumulativeComparative, averageScore, averageComparative };
}
async function _createRecord(
dateId,
searchKey,
averageScore,
averageComparative,
totalCumulativeScore,
totalCumulativeComparative,
twitter_premium,
twitter_standard,
reddit,
news
) {
let data = {
asset: searchKey,
averageScore,
averageComparative,
totalCumulativeScore,
totalCumulativeComparative,
scoreDetails: {
twitter_premium_cumulativeScore: twitter_premium.cumulativeScore,
twitter_premium_cumulativeComparative: twitter_premium.cumulativeComparative,
twitter_standard_cumulativeScore: twitter_standard.cumulativeScore,
twitter_standard_cumulativeComparative: twitter_standard.cumulativeComparative,
reddit_cumulativeScore: reddit.cumulativeScore,
reddit_cumulativeComparative: reddit.cumulativeComparative,
news_cumulativeScore: news.cumulativeScore,
news_cumulativeComparative: news.cumulativeComparative
}
};
let assetKey = h.getAssetKey(searchKey);
await retry(async () => await saveSentimentData(dateId, assetKey, data), "sentimentController saveSentimentData").catch(e => { throw e });
};
async function _replaceScore(word, score) {
let extraWords = await retry(async () => await getExtraWords(), "sentimentController _replaceScore getExtraWords").catch(e => { throw e });
extraWords[word.toLowerCase()] = score
let sortedKeys = Object.keys(extraWords).sort()
let sortedDict = {}
sortedKeys.map(key => sortedDict[key] = extraWords[key])
await retry(async () => await saveExtraWords(sortedDict), "sentimentController _replaceScore saveExtraWords").catch(e => { throw e });
l.log({
title: "🤓 Sentiment controller",
message: `Added/modified \`${word}: ${score}\``,
postToSlack: true
})
}
async function _analyse(text, extraWordsCache) {
// Fetch words from cache if needed
let extraWords = extraWordsCache
if (!extraWords) {
// Repeat cache check for Scruffy
extraWords = getExtraWordCache()
if (!extraWords) {
extraWords = await retry(async () => await getExtraWords(), "sentimentController _analyse getExtraWords").catch(e => { throw e })
updateExtraWordCache(extraWords)
};
}
let options = {
extras: extraWords
};
// Clean up text for duplicate words
let uniqueWords = text.toLowerCase().split(' ').filter((item, i, allItems) => {
return i == allItems.indexOf(item);
}).join(' ');
// Clean up text from other characters
uniqueWords = uniqueWords.replace(/'/g, ' ').replace(/"/g, ' ').replace(/`/g, ' ').replace(/\./g, '').replace(/\,/g, '').replace(/\(/g, ' ').replace(/\)/g, ' ').replace(/\:/g, ' ').replace(/;/g, ' ')
let result = await sentiment.analyze(uniqueWords, options)
return result
}
async function _analyseText(text, extraWordsCache) {
let result = await _analyse(text, extraWordsCache).catch(e => { throw e });
let positive = result.positive;
let negative = result.negative;
let score = result.score;
let comparative = result.comparative;
return { text, positive, negative, score, comparative };
}
async function _analyseResultsArray(results, extraWordsCache) {
let cumulativeScore = 0;
let cumulativeComparative = 0;
let analysed = await h.mapAsync(results, async function(result) {
let analysis = await _analyseText(result.text, extraWordsCache).catch(e => { throw e });
cumulativeScore += analysis.score;
cumulativeComparative += analysis.comparative;
return { ...result, ...analysis };
});
return { analysed, cumulativeScore, cumulativeComparative };
}
async function _analyseSubreddit(subreddit, quietMode, extraWordsCache) {
let results = await retry(async () => await getSubreddit(subreddit, quietMode), "sentimentController getSubreddit").catch(e => { throw e });
let redditBucketData = {
included: results.threads,
excluded: results.ignored_threads,
stats: {
total_analysed: results.total_analysed,
total_curated: results.total_curated,
total_sticky: results.total_sticky,
total_self: results.total_self
}
};
let { analysed, cumulativeScore, cumulativeComparative } = await _analyseResultsArray(results.threads, extraWordsCache).catch(e => { throw e });
return { reddit: { analysed, results, cumulativeScore, cumulativeComparative }, redditBucketData};
}
async function _analyseTwitter(isPremium, searchKey, pages, quietMode, extraWordsCache) {
let results = isPremium
? await retry(async () => await performPremiumSearch(searchKey, pages, quietMode || false), "sentimentController performPremiumSearch").catch(e => { throw e })
: await retry(async () => await performStandardSearch(searchKey, pages, quietMode || false), "sentimentController performStandardSearch").catch(e => { throw e })
let bucketData = {
included: results.tweets,
excluded: {
ignored_tweets: results.ignored_tweets,
ignored_retweets: results.ignored_retweets
},
stats: {
total_analysed: results.total_analysed,
total_curated: results.total_curated
}
};
let { analysed, cumulativeScore, cumulativeComparative } = await _analyseResultsArray(results.tweets, extraWordsCache).catch(e => { throw e });
return { result: { analysed, results, cumulativeScore, cumulativeComparative }, bucketData};
}
async function _analyseNews(searchKey, quietMode, extraWordsCache) {
let results = await retry(async () => await searchNews(searchKey, quietMode || false), "sentimentController searchNews").catch(e => { throw e });
let newsBucketData = {
included: results.articles,
excluded: {
old_articles: results.oldArticles,
ignored_articles: results.ignoredArticles
},
stats: {
total_analysed: results.articles.length + results.oldArticles.length + results.ignoredArticles.length,
total_curated: results.oldArticles.length + results.ignoredArticles.length
}
};
let { analysed, cumulativeScore, cumulativeComparative } = await _analyseResultsArray(results.articles, extraWordsCache).catch(e => { throw e });
return { news: { analysed, results, cumulativeScore, cumulativeComparative }, newsBucketData };
}
async function _analyseAllSources(dateId, searchKey, quietMode, twitterPremium) {
let extraWords = getExtraWordCache()
if (!extraWords) {
extraWords = await retry(async () => await getExtraWords(), "sentimentController _analyseAllSources getExtraWords").catch(e => { throw e })
updateExtraWordCache(extraWords)
};
let pages = 4;
l.log({
title: "🤓 Sentiment controller",
message: `Analysing Twitter Standard for ${searchKey}`
})
let twitterStandardResult = await _analyseTwitter(false, searchKey, pages, quietMode, extraWords).catch(e => { throw Error(`_analyseTwitter: ${e.message}`) });
let twitter_standard = twitterStandardResult.result;
let twitterStandardBucketData = twitterStandardResult.bucketData;
l.log({
title: "🤓 Sentiment controller",
message: `Analysing Reddit for ${searchKey}`
})
let { reddit, redditBucketData } = await _analyseSubreddit(searchKey, quietMode, extraWords).catch(e => { throw Error(`_analyseSubreddit: ${e.message}`) });
l.log({
title: "🤓 Sentiment controller",
message: `Analysing Bing News for ${searchKey}`
})
let { news, newsBucketData } = await _analyseNews(searchKey, quietMode, extraWords).catch(e => { throw Error(`_analyseNews: ${e.message}`) });
let twitter_premium = {
cumulativeScore: 0,
cumulativeComparative: 0,
analysed: []
};
let twitterPremiumBucketData;
if (twitterPremium) {
l.log({
title: "🤓 Sentiment controller",
message: `Analysing Twitter Premium for ${searchKey}`
})
let twitterPremiumResult = await _analyseTwitter(true, searchKey, 1, quietMode, extraWords).catch(e => { throw Error(`_analyseTwitterPremium: ${e.message}`) });
twitter_premium = twitterPremiumResult.result;
twitterPremiumBucketData = twitterPremiumResult.bucketData;
}
let { totalCumulativeScore, totalCumulativeComparative, averageScore, averageComparative } = _getTotals([
reddit,
twitter_premium,
twitter_standard,
news
]);
await _createRecord(
dateId,
searchKey,
averageScore,
averageComparative,
totalCumulativeScore,
totalCumulativeComparative,
twitter_premium,
twitter_standard,
reddit,
news
).catch(e => { throw Error(`_createRecord: ${e.message}`) });
let sentimentBucketData = [
{ currency: searchKey, source: "twitterStandard", data: twitterStandardBucketData },
{ currency: searchKey, source: "reddit", data: redditBucketData },
{ currency: searchKey, source: "news", data: newsBucketData }
]
if (twitterPremiumBucketData) {
sentimentBucketData.push({ currency: searchKey, source: "twitterPremium", data: twitterPremiumBucketData })
}
return sentimentBucketData
}
async function saveDataToBucket(data) {
let body = { allData: data }
await retry(async () => await fetch(process.env.FIREBASE_FUNCTIONS_ENDPOINT + "/benderSaveSentiment", {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
"Hermes-Auth": process.env.FUTURA_AUTH_HERMES
}
}), "sentimentController saveDataToBucket").catch((e) => { throw e });
l.log({
title: "🤓 Sentiment controller",
message: "Data saved to buckets"
})
}
exports.getSentiment = async (dateId) => {
try {
// Currently, to stay within twitter sandbox limits (250 requests per 30 days)
// we only call the twitter premium API 4 times a day (every 6 hours) x 2 assets (BTC + ETH).
let parsedDate = new Date(dateId);
let parsedHours = parsedDate.getUTCHours();
let parsedMins = parsedDate.getUTCMinutes();
let shouldGetTwitterPremium = (parsedHours % 6 === 0) && (parsedMins < 5); // give minutes buffer
l.log({
title: "🤓 Sentiment controller",
message: "** Analysing for ethereum..."
})
let ethBucketData = await _analyseAllSources(dateId, "ethereum", false, shouldGetTwitterPremium).catch(e => {
throw Error(`Error in _analyseAllSources for ${dateId}, ethereum, false, ${shouldGetTwitterPremium}: ${e.message}`)
});
l.log({
title: "🤓 Sentiment controller",
message: "** Analysing for bitcoin..."
})
let btcBucketData = await _analyseAllSources(dateId, "bitcoin", false, shouldGetTwitterPremium).catch(e => {
throw Error(`Error in _analyseAllSources for ${dateId}, bitcoin, false, ${shouldGetTwitterPremium}: ${e.message}`)
});
l.log({
title: "🤓 Sentiment controller",
message: "** Saving sentiment bucket data"
})
let combinedBucketData = ethBucketData.concat(btcBucketData)
await saveDataToBucket(combinedBucketData).catch(e => {
throw Error(`Error in saveDataToBucket: ${e.message}`)
});
l.log({
title: "🤓 Hermes Sentiment controller",
message: "** Finished saving sentiment bucket data",
})
} catch (e) {
l.logError({
title: "🤓 Hermes Sentiment controller error",
message: e.message,
details: e.stack,
})
}
};
exports.analyseTextArray = async (req, res) => {
let textArray = req.body.textArray;
if (!textArray || textArray.length === 0) {
return res.sendStatus(400)
}
let analysed = await h.mapAsync(textArray, async (text) => {
let analysis = await _analyseText(text).catch(e => {
l.logError({
title: "🤓 Hermes Sentiment analyseTextArray error",
message: e.message,
details: e.stack,
})
return
})
return { text, ...analysis };
})
res.json(analysed);
}
exports.getScore = async (req, res) => {
let text = req.body.text
if (!text) {
return res.status(400).send("No valid text")
}
let result = await _analyse(text).catch(e => {
l.logError({
title: "🤓 Hermes getScore error",
message: e.message,
details: e.stack,
})
return res.status(400).send(e.message)
})
res.json(result)
}
exports.saveScore = async (req, res) => {
let word = req.body.word
let score = Number(req.body.score)
if (!word || !Number.isInteger(score)) {
return res.status(400).send("No valid word or score")
}
console.log(word, score)
await _replaceScore(word, score).catch(e => {
l.logError({
title: "🤓 Hermes saveScore error",
message: e.message,
details: e.stack,
})
return res.status(400).send(e.message)
})
res.sendStatus(200)
}