forked from jawerty/myAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
271 lines (242 loc) · 10.4 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
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
importScripts('./Readability.js');
importScripts('./lda.js');
importScripts('./compromise.js');
importScripts('./storage.js');
importScripts('./ranking.js');
const runtimeObjects = {}
const initFeedSettings = async () => {
const updateDefaultsFeedSettings = async (feedSettings) => {
const newFeedSettings = new FeedSettings(feedSettings);
await storage.save(storage.KEYS.feed_settings, newFeedSettings)
}
if (!runtimeObjects[storage.KEYS.feed_settings]
|| Object.keys(runtimeObjects[storage.KEYS.feed_settings]).length === 0) {
console.log("init feed settings");
const newFeedSettings = new FeedSettings({});
await storage.save(storage.KEYS.feed_settings, newFeedSettings)
} else {
console.log('updating feed setting with defaults')
updateDefaultsFeedSettings(runtimeObjects[storage.KEYS.feed_settings])
}
}
const parseKeywordsFromText = (text) => {
const wordsToIgnore = ['more', 'an', 'of', 'on', 'heres', 'set', 'it', 'if', 'my', 'your', 'in', 'everyone', 'fe', 'me', 'us', 'someone', 'we', 'that', 'i', 'im', 'am', 'he', 'she', 'you', 'them', 'they', 'what', 'the', 'his', 'her', 'hers'];
const doc = nlp(text);
const namedEntities = Object.assign(doc.nouns().data(), doc.topics().data());
return namedEntities.map((entity) => {
if (entity.text.indexOf('https://') === 0 || entity.text.indexOf('https://') === 0) {
return '';
}
const parsedEntity = entity.text.replace(/[^\w\s]/gi, '').replace(/\s+/g, " ");
console.log("Found:", parsedEntity.toLowerCase());
if (parsedEntity == parseInt(parsedEntity)) {
return '';
};
if (wordsToIgnore.includes(parsedEntity.toLowerCase().trim())) {
return '';
}
if (parsedEntity.toLowerCase().length < 2) {
return '';
}
return parsedEntity.toLowerCase().trim();
}).filter((entity) => {
return entity.length > 0;
});
}
const processEngagementText = async (text, newEngagementType, sourceDomain) => {
const keywords = parseKeywordsFromText(text.join(' '));
console.log("keywords found:", keywords);
if (!runtimeObjects[storage.KEYS.keywords]) {
runtimeObjects[storage.KEYS.keywords] = await storage.get(storage.KEYS.keywords);
}
const keywordsToSave = keywords.map((keyword) => {
let pastKeywordObject;
if (keyword in runtimeObjects[storage.KEYS.keywords]) {
pastKeywordObject = runtimeObjects[storage.KEYS.keywords][keyword]
} else {
pastKeywordObject = {
text: keyword,
occurrences: 0,
history: {},
engagementTypes: {
'search-query': 0,
'meta-keywords': 0,
'meta-title': 0,
'link-click': 0,
'content-click': 0,
'input-type': 0,
'custom': 0
}
}
}
return JSON.parse(JSON.stringify(new Keyword(pastKeywordObject, newEngagementType, sourceDomain)));
});
try {
const keywordsToSaveMap = {};
for (let keywordToSave of keywordsToSave) {
keywordsToSaveMap[keywordToSave.text] = keywordToSave;
}
const newRuntimeKeywords = Object.assign(runtimeObjects[storage.KEYS.keywords], keywordsToSaveMap);
await storage.save(storage.KEYS.keywords, newRuntimeKeywords);
console.log("keywords saved", newRuntimeKeywords);
} catch(e) {
console.log("keyword save BROKE for query:", text, e);
}
}
const init = () => {
chrome.webRequest.onHeadersReceived.addListener(
async (data) => {
if (runtimeObjects[storage.KEYS.feed_settings].disableAlgorithm) {
return;
}
if (data.type === "main_frame") {
const url = data.url;
try {
const urlObj = new URL(url);
if (urlObj.search[0] === "?") {
for (let queryItem of urlObj.search.slice(1).split('&')) {
if (queryItem.split('=')[0] === 'q') {
const searchQuery = queryItem.split('=')[1].split('+');
console.log("searchQuery found:", searchQuery)
processEngagementText(searchQuery, 'search-query', urlObj.hostname)
}
}
}
} catch(e) {
console.log(e);
}
}
},
{urls: ["<all_urls>"]}
)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log("background request made:", request);
if (request.action === 'myalgorithm-init') {
sendResponse({
status: true
})
} else if (request.action === "newEngagementText") {
if (runtimeObjects[storage.KEYS.feed_settings].disableAlgorithm) {
sendResponse({
processedEngagementText: false
});
} else {
const engagementText = request.text;
processEngagementText(engagementText, request.type, request.sourceDomain);
sendResponse({
processedEngagementText: true
});
}
} else if (request.action === "getContentFeed") {
if (runtimeObjects[storage.KEYS.fetched_ts]) {
const now = new Date();
const resetTime = new Date();
resetTime.setHours(6, 0, 0, 0);
if (now.getTime() < resetTime.getTime()) {
console.log("sending back content 1")
sendResponse({
contentFeed: runtimeObjects[storage.KEYS.content_feed] || null
});
} else {
if (runtimeObjects[storage.KEYS.fetched_ts] >= resetTime.getTime()) {
console.log("sending back content 2")
sendResponse({
contentFeed: runtimeObjects[storage.KEYS.content_feed] || null
});
} else {
sendResponse({
contentFeed: null
});
}
}
} else {
sendResponse({
contentFeed: null
})
}
} else if (request.action === "saveContentFeed") {
storage.save(storage.KEYS.content_feed, request.contentFeed)
storage.save(storage.KEYS.fetched_ts, (new Date()).getTime())
sendResponse({
save: true
});
} else if (request.action === "getTopics") {
const rankedKeywords = rankKeywords(
runtimeObjects[storage.KEYS.keywords],
runtimeObjects[storage.KEYS.feed_settings]
)
if (rankedKeywords.length === 0) {
sendResponse({
topics: null
});
} else {
const topics = generateKeywordTopics(rankedKeywords, true)
sendResponse({
topics
});
}
}else if (request.action === "getSearchQueries") {
const rankedKeywords = rankKeywords(
runtimeObjects[storage.KEYS.keywords],
runtimeObjects[storage.KEYS.feed_settings]
)
let topics = []
if (rankedKeywords.length > 0) {
topics = generateKeywordTopics(rankedKeywords)
}
console.log("topics", topics)
const searchQueries = [];
for (let contentIndex = 0; contentIndex < topics.length; contentIndex += 1) {
const makeRandom = Math.floor((Math.random()*100)) > 66; // 33% random
const searchQuery = buildSearchQuery(topics, rankedKeywords, contentIndex, makeRandom);
searchQueries.push(searchQuery)
}
console.log("searchQueries", searchQueries)
sendResponse({
searchQueries
});
} else if (request.action === "getKeywords") {
if (runtimeObjects[storage.KEYS.keywords]) {
sendResponse({
keywords: Object.values(runtimeObjects[storage.KEYS.keywords])
})
}
} else if (request.action === "getFeedSettings") {
if (runtimeObjects[storage.KEYS.feed_settings]) {
sendResponse({
feedSettings: runtimeObjects[storage.KEYS.feed_settings]
})
}
} else if (request.action === "saveFeedSettings") {
if (request.newFeedSettings) {
console.log("saved feed settings", request.newFeedSettings)
runtimeObjects[storage.KEYS.feed_settings] = request.newFeedSettings;
storage.save(storage.KEYS.feed_settings, request.newFeedSettings)
sendResponse({})
}
} else if (request.action === "removeKeyword") {
const keywordToRemove = request.keyword;
if (keywordToRemove in runtimeObjects[storage.KEYS.keywords]) {
delete runtimeObjects[storage.KEYS.keywords][keywordToRemove];
storage.save(storage.KEYS.keywords, runtimeObjects[storage.KEYS.keywords])
sendResponse({});
}
} else if (request.action === "clearKeywords") {
storage.save(storage.KEYS.keywords, {});
sendResponse({});
} else if (request.action === "addTopic") {
processEngagementText([request.keyword], 'custom', null)
sendResponse({});
}
return true;
});
}
(async function() {
init();
runtimeObjects[storage.KEYS.keywords] = await storage.get(storage.KEYS.keywords);
runtimeObjects[storage.KEYS.feed_settings] = await storage.get(storage.KEYS.feed_settings);
runtimeObjects[storage.KEYS.fetched_ts] = await storage.get(storage.KEYS.fetched_ts);
runtimeObjects[storage.KEYS.content_feed] = await storage.get(storage.KEYS.content_feed);
initFeedSettings();
console.log("INIT runtime", runtimeObjects)
})();