forked from MarshaIIs/ChromeWebStoreSorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorter.js
318 lines (283 loc) · 10.4 KB
/
sorter.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
/** HOW TO USE
Copy the following link, and replace the word 'PHRASE' with your own search phrase.
https://chrome.google.com/webstore/search/PHRASE?_category=extensions
*/
main();
async function main() {
console.clear();
try {
await validateUrl();
var startPrompt = confirm("Start sorting?");
console.clear();
} catch (e) {
return;
}
if (startPrompt) {
blurPage(true);
sortWebstore();
}
}
async function stop(reason) {
stop = true;
blurPage(false);
window.scrollTo(0, 0);
if (!reason === "auto") {
console.info(
"%cThe script was force stopped\n%cDid something go wrong? :(",
"color: orange; font-weight: bold; font-size: 130%;",
""
);
}
}
async function blurPage(state) {
let style = "html { filter: blur(5px); }";
if (state) {
let styleEl = document.createElement('style');
styleEl.textContent = style;
document.head.appendChild(styleEl);
} else {
document.head.querySelectorAll("style").forEach(el => {
if (el.textContent.includes(style)) {
el.remove();
}
});
}
}
async function validateUrl() {
// Valid extensions URL example: 'https://chrome.google.com/webstore/search/PHRASE?_category=extensions'
// Adding functionality to continue sort with no filtering or when filtered for themes
const validHostname = "chrome.google.com",
validPath = "webstore/search",
validCategory = "extensions";
const hostname = window.location.hostname.toLowerCase(); // 'chrome.google.com'
const pathname = window.location.pathname.toLowerCase(), // '/webstore/search/PHRASE'
[path1, path2, searchPhrase] = pathname.split("/").slice(1),
pathFull = `${path1}/${path2}`;
const queryString = window.location.search.toLowerCase(), // ?_category=extensions'
params = new URLSearchParams(queryString),
category = params.get("_category") ?? "",
lang = params.get("hl") ?? "";
if (hostname !== validHostname) {
throw console.error(
`%cError not in Chrome Web Store!\n` +
`%cSite should be "${validHostname}"`,
"color:orange; font-size: 130%; font-weight: bold",
""
);
} else if (pathFull !== validPath) {
throw console.error(
`%cError not searching Chrome Web Store!\n` +
`%cPath should be "/${validPath}/..."`,
"color:orange; font-size: 130%; font-weight: bold",
""
);
} else if (
queryString !== `?_category=${validCategory}` &&
queryString !== `?hl=${lang}&_category=${validCategory}`
) {
console.warn(
`%cError search not filtered to "${validCategory}" !\n` +
`%cRecommend searching for "${validCategory}".`,
"color:orange; font-size: 130%; font-weight: bold",
""
);
let redirectPrompt = confirm(
`ERROR!\n${validCategory === category ? `Search seems broken.` : `Recommend searching for ${validCategory}.`}\nWant to search in ${validCategory}?`
);
if (redirectPrompt) {
console.clear();
console.info(
"%cAttempting to fix search...%c" +
"\nRemember to %crestart Sorting%c after the page loads",
"color:orange; font-size: 130%; font-weight: bold",
"",
"font-weight: bold; color: skyblue; border-bottom: solid skyblue 2px",
""
);
await new Promise(res => setTimeout(res, 2500)); // sleep 2.5 seconds
const finalURL = `https://${hostname}${pathname}?_category=${validCategory}`;
try {
console.info(
`%cSuccess!\n` + `%cTaking you to search for extensions now.`,
"color:limegreen; font-size: 130%; font-weight: bold",
""
);
await new Promise(res => setTimeout(res, 1500)); // sleep 1.5 second
window.location.assign(finalURL);
} catch (error) {
console.clear();
console.error(
`%cFatal error!\n` + `%cSorry search fix failed.\n`,
"color:orange; font-size: 130%; font-weight: bold",
""
);
throw error;
}
} else {
console.info(
`%cContinuing sort!\n` +
`%cSearching without filtering for extensions.`,
"color:orange; font-size: 130%; font-weight: bold",
""
);
}
} else {
console.info(
`%cSuccess!\n` + `%cURL is valid.`,
"color:limegreen; font-size: 130%; font-weight: bold",
""
);
}
return new Promise((resolve) => {
setTimeout(() => {
resolve("success");
}, 800);
});
}
function sortWebstore(MAX_PAGE_LOADS = 2) { // was 25. Gives ~200 results which is good for speed and for relevance of top results.
console.info(
"%cSorting search results!\n" +
"%cThis might take a moment. Be right back.",
"font-size: 130%; font-weight: bold; color: skyblue;",
""
);
let startIndex = 0;
let itemCount = 0;
let pageLoadsCount = 0;
let checkEnded = false;
let newItemCount;
startLoad(100);
loadMaxCheck();
function startLoad(max) {
startIndex++;
//document.querySelectorAll('div.h-a-Kd.a-Hd-mb')[0];
let pageBottom = document.querySelectorAll("div.h-a-Hd-mb.a-Hd-mb")[0];
pageBottom.scrollIntoView();
// scrollTo(scrollX,scrollY+1000);
// console.log(i.toString());
let items = document.querySelectorAll(
".a-d-na.a-d.webstore-test-wall-tile.a-d-zc.Xd.dd"
);
newItemCount = items.length;
if (itemCount != newItemCount) {
itemCount = newItemCount;
// console.info(
// "Loaded extensions : %c" + newItemCount,
// "font-weight: bold; color: skyblue;"
// );
}
if (startIndex > max || checkEnded) {
startIndex = 0;
itemCount = 0;
checkEnded = false;
items[newItemCount - 1].scrollIntoView(false);
sortsort();
return;
}
setTimeout(() => {
startLoad(max);
}, 500);
}
function loadMaxCheck() {
let loadIndicator = document.querySelectorAll("div.h-a-Kd.a-Hd-mb")[0];
let loadIndicatorState =
loadIndicator.attributes.style.value === "display: none;";
if (loadIndicatorState) pageLoadsCount++;
else pageLoadsCount = 0;
// console.log("Counter : " + counter);
if (pageLoadsCount > MAX_PAGE_LOADS) {
pageLoadsCount = 0;
checkEnded = true;
return;
}
setTimeout(() => {
loadMaxCheck();
}, 500);
}
function sortsort() {
let itemsNodeList = document.querySelectorAll(
".a-d-na.a-d.webstore-test-wall-tile.a-d-zc.Xd.dd"
);
let itemElemsArr = Array.from(itemsNodeList);
let logArr = [{}];
try {
itemElemsArr.forEach((itemElement) => {
itemTitle = itemElement
.querySelector("div.a-na-d-w")
.textContent.toString();
orderingNum = itemElement.attributes.hasOwnProperty("index")
? Number(
itemElement.attributes.index.value
.toString()
.replace(/,/g, "")
)
: 0;
rating_str =
itemElement.getElementsByClassName("nAtiRe").length > 0
? Number(
itemElement
.getElementsByClassName("nAtiRe")[0]
.textContent.toString()
.replace(/,/g, "")
).toString()
: "Not voted";
logArr.push({
Order: orderingNum,
Title: itemTitle,
Rating: rating_str,
});
});
} catch (err) {
throw console.error(err);
}
itemElemsArr.sort((item1, item2) => {
let item1_rating =
item1.getElementsByClassName("nAtiRe").length > 0
? Number(
item1
.getElementsByClassName("nAtiRe")[0]
.textContent.toString()
.replace(/,/g, "")
)
: 0;
let item2_rating =
item2.getElementsByClassName("nAtiRe").length > 0
? Number(
item2
.getElementsByClassName("nAtiRe")[0]
.textContent.toString()
.replace(/,/g, "")
)
: 0;
return item2_rating - item1_rating;
});
let itemRowsNodeList = document.querySelectorAll(
'.h-a-x > [role="grid"] > [role="row"]'
);
let itemRowsArr = Array.from(itemRowsNodeList);
for (let i = 0; i < itemRowsArr.length; i++) {
row_start = i * 3;
//let logMsg = i.toString() + " <--- ";
for (
let sortedRow = row_start;
sortedRow < row_start + 3 && sortedRow < itemElemsArr.length;
sortedRow++
) {
//logMsg += "1:" + sortedRow + " ";
itemRowsArr[i].appendChild(itemElemsArr[sortedRow]);
}
//console.log(logMsg);
}
// console.clear();
console.info(
"%cSorting finished!!\n%cResults are now ranked by the number of ratings they have!",
"color: limegreen; font-weight: bold; font-size: 130%;",
""
);
console.groupCollapsed("Sorted data info");
console.table(logArr.slice(1), ["Title", "Rating", "Order"]);
console.groupEnd();
stop("auto");
return;
}
}