2018-11-07 06:09:29 +00:00
|
|
|
/* global tabURL handleEvent $ $$ prefs template FIREFOX chromeLocal debounce
|
|
|
|
$create t API tWordBreak formatDate tryCatch tryJSONparse LZString
|
2018-12-11 12:40:54 +00:00
|
|
|
ignoreChromeError download */
|
2017-12-09 21:03:17 +00:00
|
|
|
'use strict';
|
|
|
|
|
2017-12-10 01:03:04 +00:00
|
|
|
window.addEventListener('showStyles:done', function _() {
|
|
|
|
window.removeEventListener('showStyles:done', _);
|
|
|
|
|
|
|
|
if (!tabURL) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
//region Init
|
|
|
|
|
|
|
|
const BODY_CLASS = 'search-results-shown';
|
|
|
|
const RESULT_ID_PREFIX = 'search-result-';
|
|
|
|
|
|
|
|
const BASE_URL = 'https://userstyles.org';
|
2018-12-10 13:14:43 +00:00
|
|
|
const JSON_URL = BASE_URL + '/styles/chrome/';
|
|
|
|
const API_URL = BASE_URL + '/api/v1/styles/';
|
2017-12-11 02:20:59 +00:00
|
|
|
const UPDATE_URL = 'https://update.userstyles.org/%.md5';
|
|
|
|
|
2020-01-28 02:36:43 +00:00
|
|
|
const STYLUS_CATEGORY = 'chrome-extension';
|
2017-12-11 02:20:59 +00:00
|
|
|
|
|
|
|
const DISPLAY_PER_PAGE = 10;
|
|
|
|
// Millisecs to wait before fetching next batch of search results.
|
|
|
|
const DELAY_AFTER_FETCHING_STYLES = 0;
|
|
|
|
// Millisecs to wait before fetching .JSON for next search result.
|
|
|
|
const DELAY_BEFORE_SEARCHING_STYLES = 0;
|
|
|
|
|
2017-12-13 22:46:32 +00:00
|
|
|
// update USO style install counter
|
|
|
|
// if the style isn't uninstalled in the popup
|
|
|
|
const PINGBACK_DELAY = 60e3;
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const BLANK_PIXEL_DATA = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAA' +
|
|
|
|
'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII=';
|
|
|
|
|
|
|
|
const CACHE_SIZE = 1e6;
|
|
|
|
const CACHE_PREFIX = 'usoSearchCache/';
|
|
|
|
const CACHE_DURATION = 24 * 3600e3;
|
2018-07-05 12:45:31 +00:00
|
|
|
const CACHE_CLEANUP_THROTTLE = 10e3;
|
|
|
|
const CACHE_CLEANUP_NEEDED = CACHE_PREFIX + 'clean?';
|
2017-12-11 02:20:59 +00:00
|
|
|
const CACHE_EXCEPT_PROPS = ['css', 'discussions', 'additional_info'];
|
|
|
|
|
|
|
|
let searchTotalPages;
|
|
|
|
let searchCurrentPage = 1;
|
2020-01-28 02:36:43 +00:00
|
|
|
let searchExhausted = 0; // 1: once, 2: twice (first host.jp, then host)
|
2017-12-11 02:20:59 +00:00
|
|
|
|
2018-12-10 13:14:43 +00:00
|
|
|
// currently active USO requests
|
|
|
|
const xhrSpoofIds = new Set();
|
|
|
|
// used as an HTTP header name to identify spoofed requests
|
|
|
|
const xhrSpoofTelltale = getRandomId();
|
2018-07-04 12:03:54 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const processedResults = [];
|
|
|
|
const unprocessedResults = [];
|
|
|
|
|
|
|
|
let loading = false;
|
|
|
|
// Category for the active tab's URL.
|
|
|
|
let category;
|
|
|
|
let scrollToFirstResult = true;
|
|
|
|
|
|
|
|
let displayedPage = 1;
|
|
|
|
let totalPages = 1;
|
|
|
|
let totalResults = 0;
|
|
|
|
|
|
|
|
// fade-in when the entry took that long to replace its placeholder
|
|
|
|
const FADEIN_THRESHOLD = 50;
|
|
|
|
|
|
|
|
const dom = {};
|
|
|
|
|
2017-12-10 01:03:04 +00:00
|
|
|
Object.assign($('#find-styles-link'), {
|
2020-01-28 02:36:43 +00:00
|
|
|
href: BASE_URL + '/styles/browse/' + getCategory(),
|
2017-12-10 01:03:04 +00:00
|
|
|
onclick(event) {
|
2017-12-11 02:20:59 +00:00
|
|
|
if (!prefs.get('popup.findStylesInline') || dom.container) {
|
2017-12-10 01:03:04 +00:00
|
|
|
handleEvent.openURLandHide.call(this, event);
|
|
|
|
return;
|
|
|
|
}
|
2017-12-11 04:35:23 +00:00
|
|
|
event.preventDefault();
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
this.textContent = this.title;
|
|
|
|
this.title = '';
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
init();
|
|
|
|
load();
|
2017-12-10 01:03:04 +00:00
|
|
|
},
|
|
|
|
});
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
return;
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function init() {
|
2017-12-11 04:35:23 +00:00
|
|
|
setTimeout(() => document.body.classList.add(BODY_CLASS));
|
|
|
|
|
|
|
|
$('#find-styles-inline-group').classList.add('hidden');
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.container = $('#search-results');
|
2017-12-11 20:25:41 +00:00
|
|
|
dom.container.dataset.empty = '';
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.error = $('#search-results-error');
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.nav = {};
|
|
|
|
const navOnClick = {prev, next};
|
|
|
|
for (const place of ['top', 'bottom']) {
|
2017-12-11 10:03:03 +00:00
|
|
|
const nav = $(`.search-results-nav[data-type="${place}"]`);
|
2017-12-11 02:20:59 +00:00
|
|
|
nav.appendChild(template.searchNav.cloneNode(true));
|
|
|
|
dom.nav[place] = nav;
|
2017-12-11 10:03:03 +00:00
|
|
|
for (const child of $$('[data-type]', nav)) {
|
|
|
|
const type = child.dataset.type;
|
|
|
|
child.onclick = navOnClick[type];
|
|
|
|
nav['_' + type] = child;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.list = $('#search-results-list');
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 20:25:41 +00:00
|
|
|
addEventListener('scroll', loadMoreIfNeeded, {passive: true});
|
2017-12-13 21:49:11 +00:00
|
|
|
|
2017-12-13 20:13:35 +00:00
|
|
|
if (FIREFOX) {
|
2017-12-19 04:05:07 +00:00
|
|
|
let lastShift;
|
2017-12-13 20:13:35 +00:00
|
|
|
addEventListener('resize', () => {
|
|
|
|
const scrollbarWidth = window.innerWidth - document.scrollingElement.clientWidth;
|
2017-12-19 04:05:07 +00:00
|
|
|
const shift = document.body.getBoundingClientRect().left;
|
|
|
|
if (!scrollbarWidth || shift === lastShift) return;
|
|
|
|
lastShift = shift;
|
|
|
|
document.body.style.setProperty('padding',
|
|
|
|
`0 ${scrollbarWidth + shift}px 0 ${-shift}px`, 'important');
|
|
|
|
}, {passive: true});
|
2017-12-13 20:13:35 +00:00
|
|
|
}
|
2017-12-11 20:25:41 +00:00
|
|
|
|
2018-11-15 13:46:52 +00:00
|
|
|
addEventListener('styleDeleted', ({detail: {style: {id}}}) => {
|
2017-12-13 21:49:11 +00:00
|
|
|
const result = processedResults.find(r => r.installedStyleId === id);
|
|
|
|
if (result) {
|
|
|
|
result.installed = false;
|
|
|
|
result.installedStyleId = -1;
|
2018-11-07 06:09:29 +00:00
|
|
|
window.clearTimeout(result.pingbackTimer);
|
2017-12-13 21:49:11 +00:00
|
|
|
renderActionButtons($('#' + RESULT_ID_PREFIX + result.id));
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
|
|
|
});
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 04:35:23 +00:00
|
|
|
addEventListener('styleAdded', ({detail: {style: {id, md5Url}}}) => {
|
2017-12-13 21:49:11 +00:00
|
|
|
const usoId = parseInt(md5Url && md5Url.match(/\d+|$/)[0]);
|
|
|
|
const result = usoId && processedResults.find(r => r.id === usoId);
|
|
|
|
if (result) {
|
|
|
|
result.installed = true;
|
|
|
|
result.installedStyleId = id;
|
|
|
|
renderActionButtons($('#' + RESULT_ID_PREFIX + usoId));
|
2017-12-10 01:03:04 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
});
|
2018-07-05 12:45:31 +00:00
|
|
|
|
|
|
|
chromeLocal.getValue(CACHE_CLEANUP_NEEDED).then(value =>
|
|
|
|
value && debounce(cleanupCache, CACHE_CLEANUP_THROTTLE));
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
//endregion
|
|
|
|
//region Loader
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/**
|
|
|
|
* Sets loading status of search results.
|
|
|
|
* @param {Boolean} isLoading If search results are idle (false) or still loading (true).
|
|
|
|
*/
|
|
|
|
function setLoading(isLoading) {
|
|
|
|
if (loading !== isLoading) {
|
|
|
|
loading = isLoading;
|
|
|
|
// Refresh elements that depend on `loading` state.
|
|
|
|
render();
|
|
|
|
}
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function showSpinner(parent) {
|
|
|
|
parent = parent instanceof Node ? parent : $(parent);
|
|
|
|
parent.appendChild($create('.lds-spinner',
|
|
|
|
new Array(12).fill($create('div')).map(e => e.cloneNode())));
|
|
|
|
}
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/** Increments displayedPage and loads results. */
|
|
|
|
function next() {
|
|
|
|
if (loading) {
|
|
|
|
debounce(next, 100);
|
|
|
|
return;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
displayedPage += 1;
|
|
|
|
scrollToFirstResult = true;
|
|
|
|
render();
|
|
|
|
loadMoreIfNeeded();
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/** Decrements currentPage and loads results. */
|
|
|
|
function prev() {
|
|
|
|
if (loading) {
|
|
|
|
debounce(next, 100);
|
|
|
|
return;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
displayedPage = Math.max(1, displayedPage - 1);
|
|
|
|
scrollToFirstResult = true;
|
|
|
|
render();
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/**
|
|
|
|
* Display error message to user.
|
|
|
|
* @param {string} message Message to display to user.
|
|
|
|
*/
|
|
|
|
function error(reason) {
|
2017-12-19 02:29:21 +00:00
|
|
|
dom.error.textContent = reason === 404 ? t('searchResultNoneFound') : reason;
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.error.classList.remove('hidden');
|
2017-12-11 19:26:33 +00:00
|
|
|
dom.container.classList.toggle('hidden', !processedResults.length);
|
|
|
|
document.body.classList.toggle('search-results-shown', processedResults.length > 0);
|
2017-12-19 02:29:21 +00:00
|
|
|
if (dom.error.getBoundingClientRect().bottom < 0) {
|
|
|
|
dom.error.scrollIntoView({behavior: 'smooth', block: 'start'});
|
2017-12-11 19:26:33 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/**
|
|
|
|
* Initializes search results container, starts fetching results.
|
|
|
|
*/
|
|
|
|
function load() {
|
2020-01-28 02:36:43 +00:00
|
|
|
if (searchExhausted > 1) {
|
2017-12-11 02:20:59 +00:00
|
|
|
if (!processedResults.length) {
|
|
|
|
error(404);
|
|
|
|
}
|
|
|
|
return;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
setLoading(true);
|
|
|
|
dom.container.classList.remove('hidden');
|
|
|
|
dom.error.classList.add('hidden');
|
|
|
|
|
|
|
|
category = category || getCategory();
|
|
|
|
|
|
|
|
search({category})
|
|
|
|
.then(function process(results) {
|
2020-01-28 02:36:43 +00:00
|
|
|
const data = results.data.filter(sameCategoryNoDupes);
|
2017-12-13 04:46:28 +00:00
|
|
|
|
2020-01-28 02:36:43 +00:00
|
|
|
if (!data.length && searchExhausted <= 1) {
|
|
|
|
const old = category;
|
|
|
|
const uso = (processedResults[0] || {}).subcategory;
|
|
|
|
category = uso !== category && uso || getCategory({retry: true});
|
|
|
|
if (category !== old) return search({category, restart: true}).then(process);
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-13 04:46:28 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const numIrrelevant = results.data.length - data.length;
|
2020-01-28 02:36:43 +00:00
|
|
|
totalResults += results.current_page === 1 ? results.total_entries : 0;
|
2017-12-11 02:20:59 +00:00
|
|
|
totalResults = Math.max(0, totalResults - numIrrelevant);
|
|
|
|
totalPages = Math.ceil(totalResults / DISPLAY_PER_PAGE);
|
|
|
|
|
2017-12-13 04:46:28 +00:00
|
|
|
setLoading(false);
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
if (data.length) {
|
|
|
|
unprocessedResults.push(...data);
|
|
|
|
processNextResult();
|
|
|
|
} else if (numIrrelevant) {
|
|
|
|
load();
|
2020-01-28 02:36:43 +00:00
|
|
|
} else if (!processedResults.length) {
|
2017-12-11 02:20:59 +00:00
|
|
|
return Promise.reject(404);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(error);
|
|
|
|
}
|
|
|
|
|
2017-12-11 20:25:41 +00:00
|
|
|
function loadMoreIfNeeded(event) {
|
2017-12-11 20:45:21 +00:00
|
|
|
let pageToPrefetch = displayedPage;
|
2017-12-11 20:25:41 +00:00
|
|
|
if (event instanceof Event) {
|
2017-12-11 20:45:21 +00:00
|
|
|
if ((loadMoreIfNeeded.prefetchedPage || 0) <= pageToPrefetch &&
|
|
|
|
document.scrollingElement.scrollTop > document.scrollingElement.scrollHeight / 2) {
|
|
|
|
loadMoreIfNeeded.prefetchedPage = ++pageToPrefetch;
|
2017-12-11 20:25:41 +00:00
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2017-12-11 20:45:21 +00:00
|
|
|
if (processedResults.length < pageToPrefetch * DISPLAY_PER_PAGE) {
|
2017-12-11 02:20:59 +00:00
|
|
|
setTimeout(load, DELAY_BEFORE_SEARCHING_STYLES);
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/**
|
|
|
|
* Processes the next search result in `unprocessedResults` and adds to `processedResults`.
|
|
|
|
* Skips installed/non-applicable styles.
|
|
|
|
* Fetches more search results if unprocessedResults is empty.
|
|
|
|
* Recurses until shouldLoadMore() is false.
|
|
|
|
*/
|
|
|
|
function processNextResult() {
|
|
|
|
const result = unprocessedResults.shift();
|
|
|
|
if (!result) {
|
|
|
|
loadMoreIfNeeded();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const md5Url = UPDATE_URL.replace('%', result.id);
|
2018-11-07 06:09:29 +00:00
|
|
|
API.styleExists({md5Url}).then(exist => {
|
|
|
|
if (exist) {
|
2017-12-11 02:20:59 +00:00
|
|
|
totalResults = Math.max(0, totalResults - 1);
|
2017-12-09 21:03:17 +00:00
|
|
|
} else {
|
2017-12-11 02:20:59 +00:00
|
|
|
processedResults.push(result);
|
|
|
|
render();
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2018-11-07 06:09:29 +00:00
|
|
|
setTimeout(processNextResult, !exist && DELAY_AFTER_FETCHING_STYLES);
|
2017-12-11 02:20:59 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
//endregion
|
|
|
|
//region UI
|
|
|
|
|
|
|
|
function render() {
|
|
|
|
let start = (displayedPage - 1) * DISPLAY_PER_PAGE;
|
|
|
|
const end = displayedPage * DISPLAY_PER_PAGE;
|
|
|
|
|
|
|
|
let plantAt = 0;
|
|
|
|
let slot = dom.list.children[0];
|
|
|
|
|
|
|
|
// keep rendered elements with ids in the range of interest
|
|
|
|
while (
|
|
|
|
plantAt < DISPLAY_PER_PAGE &&
|
|
|
|
slot && slot.id === 'search-result-' + (processedResults[start] || {}).id
|
|
|
|
) {
|
|
|
|
slot = slot.nextElementSibling;
|
|
|
|
plantAt++;
|
|
|
|
start++;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const plantEntry = entry => {
|
|
|
|
if (slot) {
|
|
|
|
dom.list.replaceChild(entry, slot);
|
|
|
|
slot = entry.nextElementSibling;
|
2017-12-09 21:03:17 +00:00
|
|
|
} else {
|
2017-12-11 02:20:59 +00:00
|
|
|
dom.list.appendChild(entry);
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
entry.classList.toggle('search-result-fadein',
|
|
|
|
!slot || performance.now() - slot._plantedTime > FADEIN_THRESHOLD);
|
|
|
|
return entry;
|
|
|
|
};
|
|
|
|
|
|
|
|
while (start < Math.min(end, processedResults.length)) {
|
|
|
|
plantEntry(createSearchResultNode(processedResults[start++]));
|
|
|
|
plantAt++;
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
for (const place in dom.nav) {
|
|
|
|
const nav = dom.nav[place];
|
|
|
|
nav._prev.disabled = displayedPage <= 1;
|
|
|
|
nav._next.disabled = displayedPage >= totalPages;
|
|
|
|
nav._page.textContent = displayedPage;
|
|
|
|
nav._total.textContent = totalPages;
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
// Fill in remaining search results with blank results + spinners
|
|
|
|
const maxResults = end > totalResults &&
|
|
|
|
totalResults % DISPLAY_PER_PAGE ||
|
|
|
|
DISPLAY_PER_PAGE;
|
|
|
|
while (plantAt < maxResults) {
|
|
|
|
if (!slot || slot.id.startsWith(RESULT_ID_PREFIX)) {
|
|
|
|
const entry = plantEntry(template.emptySearchResult.cloneNode(true));
|
|
|
|
entry._plantedTime = performance.now();
|
|
|
|
showSpinner(entry);
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
plantAt++;
|
2017-12-11 10:03:03 +00:00
|
|
|
if (!processedResults.length) {
|
|
|
|
break;
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
while (dom.list.children.length > maxResults) {
|
|
|
|
dom.list.lastElementChild.remove();
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 20:25:41 +00:00
|
|
|
if (processedResults.length && 'empty' in dom.container.dataset) {
|
|
|
|
delete dom.container.dataset.empty;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (scrollToFirstResult && (!FIREFOX || FIREFOX >= 55)) {
|
|
|
|
debounce(doScrollToFirstResult);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function doScrollToFirstResult() {
|
|
|
|
if (dom.container.scrollHeight > window.innerHeight * 2) {
|
2017-12-11 02:20:59 +00:00
|
|
|
scrollToFirstResult = false;
|
2017-12-11 20:25:41 +00:00
|
|
|
dom.container.scrollIntoView({behavior: 'smooth', block: 'start'});
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
|
|
|
}
|
2017-12-10 09:00:40 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/**
|
|
|
|
* Constructs and adds the given search result to the popup's Search Results container.
|
|
|
|
* @param {Object} result The SearchResult object from userstyles.org
|
|
|
|
*/
|
|
|
|
function createSearchResultNode(result) {
|
|
|
|
/*
|
|
|
|
userstyleSearchResult format: {
|
|
|
|
id: 100835,
|
|
|
|
name: "Reddit Flat Dark",
|
|
|
|
screenshot_url: "19339_after.png",
|
|
|
|
description: "...",
|
|
|
|
user: {
|
|
|
|
id: 48470,
|
|
|
|
name: "holloh"
|
|
|
|
},
|
|
|
|
style_settings: [...]
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
*/
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const entry = template.searchResult.cloneNode(true);
|
|
|
|
Object.assign(entry, {
|
|
|
|
_result: result,
|
|
|
|
id: RESULT_ID_PREFIX + result.id,
|
|
|
|
});
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
Object.assign($('.search-result-title', entry), {
|
|
|
|
onclick: handleEvent.openURLandHide,
|
|
|
|
href: BASE_URL + result.url
|
|
|
|
});
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const displayedName = result.name.length < 300 ? result.name : result.name.slice(0, 300) + '...';
|
|
|
|
$('.search-result-title span', entry).textContent = tWordBreak(displayedName);
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const screenshot = $('.search-result-screenshot', entry);
|
|
|
|
let url = result.screenshot_url;
|
|
|
|
if (!url) {
|
|
|
|
url = BLANK_PIXEL_DATA;
|
|
|
|
screenshot.classList.add('no-screenshot');
|
|
|
|
} else if (/^[0-9]*_after.(jpe?g|png|gif)$/i.test(url)) {
|
|
|
|
url = BASE_URL + '/style_screenshot_thumbnails/' + url;
|
|
|
|
}
|
|
|
|
screenshot.src = url;
|
|
|
|
if (url !== BLANK_PIXEL_DATA) {
|
|
|
|
screenshot.classList.add('search-result-fadein');
|
|
|
|
screenshot.onload = () => {
|
|
|
|
screenshot.classList.remove('search-result-fadein');
|
|
|
|
};
|
2017-12-10 01:03:04 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const description = result.description
|
2017-12-11 10:03:03 +00:00
|
|
|
.replace(/<[^>]*>/g, ' ')
|
|
|
|
.replace(/([^.][.。?!]|[\s,].{50,70})\s+/g, '$1\n')
|
|
|
|
.replace(/([\r\n]\s*){3,}/g, '\n\n');
|
2017-12-11 02:20:59 +00:00
|
|
|
Object.assign($('.search-result-description', entry), {
|
|
|
|
textContent: description,
|
|
|
|
title: description,
|
|
|
|
});
|
|
|
|
|
2017-12-11 10:03:03 +00:00
|
|
|
Object.assign($('[data-type="author"] a', entry), {
|
2017-12-11 02:20:59 +00:00
|
|
|
textContent: result.user.name,
|
|
|
|
title: result.user.name,
|
|
|
|
href: BASE_URL + '/users/' + result.user.id,
|
2017-12-11 10:03:03 +00:00
|
|
|
onclick: handleEvent.openURLandHide,
|
2017-12-11 02:20:59 +00:00
|
|
|
});
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
let ratingClass;
|
|
|
|
let ratingValue = result.rating;
|
|
|
|
if (ratingValue === null) {
|
|
|
|
ratingClass = 'none';
|
2017-12-11 04:35:23 +00:00
|
|
|
ratingValue = '';
|
2017-12-11 02:20:59 +00:00
|
|
|
} else if (ratingValue >= 2.5) {
|
|
|
|
ratingClass = 'good';
|
|
|
|
ratingValue = ratingValue.toFixed(1);
|
|
|
|
} else if (ratingValue >= 1.5) {
|
|
|
|
ratingClass = 'okay';
|
|
|
|
ratingValue = ratingValue.toFixed(1);
|
|
|
|
} else {
|
|
|
|
ratingClass = 'bad';
|
|
|
|
ratingValue = ratingValue.toFixed(1);
|
2017-12-10 01:03:04 +00:00
|
|
|
}
|
2017-12-11 10:03:03 +00:00
|
|
|
$('[data-type="rating"]', entry).dataset.class = ratingClass;
|
|
|
|
$('[data-type="rating"] dd', entry).textContent = ratingValue;
|
|
|
|
|
|
|
|
Object.assign($('[data-type="updated"] time', entry), {
|
2017-12-11 04:35:23 +00:00
|
|
|
dateTime: result.updated,
|
2017-12-23 00:11:46 +00:00
|
|
|
textContent: formatDate(result.updated)
|
2017-12-11 04:35:23 +00:00
|
|
|
});
|
2017-12-11 10:03:03 +00:00
|
|
|
|
|
|
|
$('[data-type="weekly"] dd', entry).textContent = formatNumber(result.weekly_install_count);
|
|
|
|
$('[data-type="total"] dd', entry).textContent = formatNumber(result.total_install_count);
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
renderActionButtons(entry);
|
|
|
|
return entry;
|
|
|
|
}
|
2017-12-10 01:03:04 +00:00
|
|
|
|
2017-12-11 10:03:03 +00:00
|
|
|
function formatNumber(num) {
|
|
|
|
return (
|
|
|
|
num > 1e9 ? (num / 1e9).toFixed(1) + 'B' :
|
|
|
|
num > 10e6 ? (num / 1e6).toFixed(0) + 'M' :
|
|
|
|
num > 1e6 ? (num / 1e6).toFixed(1) + 'M' :
|
|
|
|
num > 10e3 ? (num / 1e3).toFixed(0) + 'k' :
|
|
|
|
num > 1e3 ? (num / 1e3).toFixed(1) + 'k' :
|
|
|
|
num
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function renderActionButtons(entry) {
|
2017-12-13 21:49:11 +00:00
|
|
|
if (!entry) {
|
|
|
|
return;
|
|
|
|
}
|
2017-12-11 19:26:33 +00:00
|
|
|
const result = entry._result;
|
|
|
|
|
|
|
|
if (result.installed && !('installed' in entry.dataset)) {
|
|
|
|
entry.dataset.installed = '';
|
2017-12-19 02:30:40 +00:00
|
|
|
$('.search-result-status', entry).textContent = t('clickToUninstall');
|
2017-12-11 19:26:33 +00:00
|
|
|
} else if (!result.installed && 'installed' in entry.dataset) {
|
|
|
|
delete entry.dataset.installed;
|
|
|
|
$('.search-result-status', entry).textContent = '';
|
|
|
|
}
|
|
|
|
|
2017-12-11 04:35:23 +00:00
|
|
|
const screenshot = $('.search-result-screenshot', entry);
|
2017-12-11 19:26:33 +00:00
|
|
|
screenshot.onclick = result.installed ? onUninstallClicked : onInstallClicked;
|
2017-12-19 02:30:40 +00:00
|
|
|
screenshot.title = result.installed ? '' : t('installButton');
|
2017-12-11 04:35:23 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const uninstallButton = $('.search-result-uninstall', entry);
|
|
|
|
uninstallButton.onclick = onUninstallClicked;
|
|
|
|
|
|
|
|
const installButton = $('.search-result-install', entry);
|
|
|
|
installButton.onclick = onInstallClicked;
|
|
|
|
if ((result.style_settings || []).length > 0) {
|
|
|
|
// Style has customizations
|
|
|
|
installButton.classList.add('customize');
|
|
|
|
uninstallButton.classList.add('customize');
|
|
|
|
|
|
|
|
const customizeButton = $('.search-result-customize', entry);
|
|
|
|
customizeButton.dataset.href = BASE_URL + result.url;
|
|
|
|
customizeButton.dataset.sendMessage = JSON.stringify({method: 'openSettings'});
|
|
|
|
customizeButton.classList.remove('hidden');
|
|
|
|
customizeButton.onclick = function (event) {
|
|
|
|
event.stopPropagation();
|
|
|
|
handleEvent.openURLandHide.call(this, event);
|
|
|
|
};
|
2017-12-10 01:03:04 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function onUninstallClicked(event) {
|
|
|
|
event.stopPropagation();
|
|
|
|
const entry = this.closest('.search-result');
|
2017-12-13 22:13:16 +00:00
|
|
|
saveScrollPosition(entry);
|
2018-11-07 06:09:29 +00:00
|
|
|
API.deleteStyle(entry._result.installedStyleId)
|
2017-12-13 22:13:16 +00:00
|
|
|
.then(restoreScrollPosition);
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
/** Installs the current userstyleSearchResult into Stylus. */
|
|
|
|
function onInstallClicked(event) {
|
|
|
|
event.stopPropagation();
|
|
|
|
|
|
|
|
const entry = this.closest('.search-result');
|
|
|
|
const result = entry._result;
|
|
|
|
const installButton = $('.search-result-install', entry);
|
|
|
|
|
|
|
|
showSpinner(entry);
|
2017-12-13 22:13:16 +00:00
|
|
|
saveScrollPosition(entry);
|
2017-12-11 02:20:59 +00:00
|
|
|
installButton.disabled = true;
|
2017-12-11 04:35:23 +00:00
|
|
|
entry.style.setProperty('pointer-events', 'none', 'important');
|
2017-12-11 02:20:59 +00:00
|
|
|
|
|
|
|
// Fetch settings to see if we should display "configure" button
|
|
|
|
Promise.all([
|
|
|
|
fetchStyleJson(result),
|
|
|
|
fetchStyleSettings(result),
|
2018-11-18 13:30:47 +00:00
|
|
|
API.download({url: UPDATE_URL.replace('%', result.id)})
|
2017-12-11 02:20:59 +00:00
|
|
|
])
|
2018-11-18 13:30:47 +00:00
|
|
|
.then(([style, settings, md5]) => {
|
2017-12-13 22:46:32 +00:00
|
|
|
pingback(result);
|
2017-12-11 02:20:59 +00:00
|
|
|
// show a 'config-on-homepage' icon in the popup
|
|
|
|
style.updateUrl += settings.length ? '?' : '';
|
2018-11-18 13:30:47 +00:00
|
|
|
style.originalMd5 = md5;
|
2018-11-07 06:09:29 +00:00
|
|
|
return API.installStyle(style);
|
2017-12-11 02:20:59 +00:00
|
|
|
})
|
|
|
|
.catch(reason => {
|
|
|
|
const usoId = result.id;
|
2018-01-01 17:02:49 +00:00
|
|
|
console.debug('install:saveStyle(usoID:', usoId, ') => [ERROR]: ', reason);
|
2017-12-19 02:29:21 +00:00
|
|
|
error('Error while downloading usoID:' + usoId + '\nReason: ' + reason);
|
2017-12-11 02:20:59 +00:00
|
|
|
})
|
|
|
|
.then(() => {
|
|
|
|
$.remove('.lds-spinner', entry);
|
|
|
|
installButton.disabled = false;
|
2017-12-11 04:35:23 +00:00
|
|
|
entry.style.pointerEvents = '';
|
2017-12-13 22:13:16 +00:00
|
|
|
restoreScrollPosition();
|
2017-12-11 02:20:59 +00:00
|
|
|
});
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function fetchStyleSettings(result) {
|
|
|
|
return result.style_settings ||
|
|
|
|
fetchStyle(result.id).then(style => {
|
|
|
|
result.style_settings = style.style_settings || [];
|
|
|
|
return result.style_settings;
|
|
|
|
});
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
2017-12-13 22:46:32 +00:00
|
|
|
function pingback(result) {
|
2018-11-07 06:09:29 +00:00
|
|
|
const wnd = window;
|
|
|
|
// FIXME: move this to background page and create an API like installUSOStyle
|
2018-01-01 17:02:49 +00:00
|
|
|
result.pingbackTimer = wnd.setTimeout(wnd.download, PINGBACK_DELAY,
|
2017-12-13 22:46:32 +00:00
|
|
|
BASE_URL + '/styles/install/' + result.id + '?source=stylish-ch');
|
|
|
|
}
|
|
|
|
|
2017-12-13 22:13:16 +00:00
|
|
|
function saveScrollPosition(entry) {
|
|
|
|
dom.scrollPosition = entry.getBoundingClientRect().top;
|
|
|
|
dom.scrollPositionElement = entry;
|
|
|
|
}
|
|
|
|
|
|
|
|
function restoreScrollPosition() {
|
|
|
|
const t0 = performance.now();
|
|
|
|
new MutationObserver((mutations, observer) => {
|
|
|
|
if (performance.now() - t0 < 1000) {
|
|
|
|
window.scrollBy(0, dom.scrollPositionElement.getBoundingClientRect().top - dom.scrollPosition);
|
|
|
|
}
|
|
|
|
observer.disconnect();
|
|
|
|
}).observe(document.body, {childList: true, subtree: true, attributes: true});
|
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
//endregion
|
|
|
|
//region USO API wrapper
|
|
|
|
|
2017-12-09 21:03:17 +00:00
|
|
|
/**
|
|
|
|
* Resolves the Userstyles.org "category" for a given URL.
|
|
|
|
*/
|
2020-01-28 02:36:43 +00:00
|
|
|
function getCategory({retry} = {}) {
|
2017-12-11 02:20:59 +00:00
|
|
|
const u = tryCatch(() => new URL(tabURL));
|
2017-12-09 21:03:17 +00:00
|
|
|
if (!u) {
|
2017-12-11 02:20:59 +00:00
|
|
|
// Invalid URL
|
|
|
|
return '';
|
2017-12-09 21:03:17 +00:00
|
|
|
} else if (u.protocol === 'file:') {
|
2017-12-11 02:20:59 +00:00
|
|
|
return 'file:';
|
2017-12-09 21:03:17 +00:00
|
|
|
} else if (u.protocol === location.protocol) {
|
2020-01-28 02:36:43 +00:00
|
|
|
return STYLUS_CATEGORY;
|
2017-12-09 21:03:17 +00:00
|
|
|
} else {
|
2020-01-28 02:36:43 +00:00
|
|
|
const parts = u.hostname.replace(/\.(?:com?|org)(\.\w{2,3})$/, '$1').split('.');
|
|
|
|
const [tld, main = u.hostname, third, fourth] = parts.reverse();
|
|
|
|
const keepTld = !retry && !(
|
|
|
|
tld === 'com' ||
|
|
|
|
tld === 'org' && main !== 'userstyles'
|
|
|
|
);
|
|
|
|
const keepThird = !retry && (
|
|
|
|
fourth ||
|
|
|
|
third && third !== 'www' && third !== 'm'
|
|
|
|
);
|
2020-02-22 12:37:22 +00:00
|
|
|
return (keepThird && `${third}.` || '') + main + (keepTld || keepThird ? `.${tld}` : '');
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-28 02:36:43 +00:00
|
|
|
function sameCategoryNoDupes(result) {
|
|
|
|
return (
|
|
|
|
result.subcategory &&
|
|
|
|
!processedResults.some(pr => pr.id === result.id) &&
|
|
|
|
(category !== STYLUS_CATEGORY || /\bStylus\b/i.test(result.name + result.description)) &&
|
2020-02-22 12:37:22 +00:00
|
|
|
category.split('.').includes(result.subcategory.split('.')[0])
|
2017-12-11 02:20:59 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2017-12-09 21:03:17 +00:00
|
|
|
/**
|
|
|
|
* Fetches the JSON style object from userstyles.org (containing code, sections, updateUrl, etc).
|
2017-12-11 10:26:07 +00:00
|
|
|
* Stores (caches) the JSON within the given result, to avoid unnecessary network usage.
|
2017-12-09 21:03:17 +00:00
|
|
|
* Style JSON is fetched from the /styles/chrome/{id}.json endpoint.
|
2017-12-11 10:26:07 +00:00
|
|
|
* @param {Object} result A search result object from userstyles.org
|
2017-12-09 21:03:17 +00:00
|
|
|
* @returns {Promise<Object>} Promises the response as a JSON object.
|
|
|
|
*/
|
2017-12-11 10:26:07 +00:00
|
|
|
function fetchStyleJson(result) {
|
|
|
|
return Promise.resolve(
|
|
|
|
result.json ||
|
2018-12-10 13:14:43 +00:00
|
|
|
downloadFromUSO(JSON_URL + result.id + '.json').then(json => {
|
2017-12-11 10:26:07 +00:00
|
|
|
result.json = json;
|
|
|
|
return json;
|
|
|
|
}));
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches style information from userstyles.org's /api/v1/styles/{ID} API.
|
|
|
|
* @param {number} userstylesId The internal "ID" for a style on userstyles.org
|
|
|
|
* @returns {Promise<Object>} An object containing info about the style, e.g. name, author, etc.
|
|
|
|
*/
|
|
|
|
function fetchStyle(userstylesId) {
|
2017-12-12 14:35:38 +00:00
|
|
|
return readCache(userstylesId).then(json =>
|
|
|
|
json ||
|
2018-12-10 13:14:43 +00:00
|
|
|
downloadFromUSO(API_URL + userstylesId).then(writeCache));
|
2017-12-09 21:03:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches (and JSON-parses) search results from a userstyles.org search API.
|
2017-12-11 02:20:59 +00:00
|
|
|
* Automatically sets searchCurrentPage and searchTotalPages.
|
2017-12-09 21:03:17 +00:00
|
|
|
* @param {string} category The usrestyles.org "category" (subcategory) OR a any search string.
|
|
|
|
* @return {Object} Response object from userstyles.org
|
|
|
|
*/
|
2017-12-11 02:20:59 +00:00
|
|
|
function search({category, restart}) {
|
|
|
|
if (restart) {
|
|
|
|
searchCurrentPage = 1;
|
|
|
|
searchTotalPages = undefined;
|
|
|
|
}
|
|
|
|
if (searchTotalPages !== undefined && searchCurrentPage > searchTotalPages) {
|
2017-12-10 07:08:39 +00:00
|
|
|
return Promise.resolve({'data':[]});
|
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
|
2018-12-10 13:14:43 +00:00
|
|
|
const searchURL = API_URL + 'subcategory' +
|
2017-12-10 07:08:39 +00:00
|
|
|
'?search=' + encodeURIComponent(category) +
|
2017-12-11 02:20:59 +00:00
|
|
|
'&page=' + searchCurrentPage +
|
2018-11-28 04:39:35 +00:00
|
|
|
'&per_page=10' +
|
2017-12-10 07:08:39 +00:00
|
|
|
'&country=NA';
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
const cacheKey = category + '/' + searchCurrentPage;
|
2017-12-10 07:08:39 +00:00
|
|
|
|
|
|
|
return readCache(cacheKey)
|
2017-12-12 14:35:38 +00:00
|
|
|
.then(json =>
|
|
|
|
json ||
|
2018-12-10 13:14:43 +00:00
|
|
|
downloadFromUSO(searchURL).then(writeCache))
|
2017-12-10 07:08:39 +00:00
|
|
|
.then(json => {
|
2017-12-11 02:20:59 +00:00
|
|
|
searchCurrentPage = json.current_page + 1;
|
|
|
|
searchTotalPages = json.total_pages;
|
2020-01-28 02:36:43 +00:00
|
|
|
searchExhausted += searchCurrentPage > searchTotalPages;
|
2017-12-10 07:08:39 +00:00
|
|
|
return json;
|
2017-12-09 21:03:17 +00:00
|
|
|
}).catch(reason => {
|
2020-01-28 02:36:43 +00:00
|
|
|
searchExhausted++;
|
2017-12-10 07:08:39 +00:00
|
|
|
return Promise.reject(reason);
|
2017-12-09 21:03:17 +00:00
|
|
|
});
|
2017-12-10 07:08:39 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
//endregion
|
|
|
|
//region Cache
|
|
|
|
|
2017-12-10 07:08:39 +00:00
|
|
|
function readCache(id) {
|
2017-12-11 02:20:59 +00:00
|
|
|
const key = CACHE_PREFIX + id;
|
2018-01-01 17:02:49 +00:00
|
|
|
return chromeLocal.getValue(key).then(item => {
|
2017-12-11 02:20:59 +00:00
|
|
|
if (!cacheItemExpired(item)) {
|
2018-01-01 17:02:49 +00:00
|
|
|
return chromeLocal.loadLZStringScript().then(() =>
|
|
|
|
tryJSONparse(LZString.decompressFromUTF16(item.payload)));
|
2017-12-11 02:20:59 +00:00
|
|
|
} else if (item) {
|
|
|
|
chrome.storage.local.remove(key);
|
2017-12-10 07:08:39 +00:00
|
|
|
}
|
2017-12-09 21:03:17 +00:00
|
|
|
});
|
|
|
|
}
|
2017-12-10 07:08:39 +00:00
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
function writeCache(data, debounced) {
|
2017-12-12 14:35:38 +00:00
|
|
|
data.id = data.id || category + '/' + data.current_page;
|
|
|
|
for (const prop of CACHE_EXCEPT_PROPS) {
|
|
|
|
delete data[prop];
|
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
if (!debounced) {
|
2017-12-12 14:35:38 +00:00
|
|
|
// using plain setTimeout because debounce() replaces previous parameters
|
|
|
|
setTimeout(writeCache, 100, data, true);
|
2017-12-11 02:20:59 +00:00
|
|
|
return data;
|
|
|
|
} else {
|
2018-07-05 12:45:31 +00:00
|
|
|
chromeLocal.setValue(CACHE_CLEANUP_NEEDED, true);
|
2017-12-11 02:20:59 +00:00
|
|
|
debounce(cleanupCache, CACHE_CLEANUP_THROTTLE);
|
2018-01-01 17:02:49 +00:00
|
|
|
return chromeLocal.loadLZStringScript().then(() =>
|
|
|
|
chromeLocal.setValue(CACHE_PREFIX + data.id, {
|
|
|
|
payload: LZString.compressToUTF16(JSON.stringify(data)),
|
|
|
|
date: Date.now(),
|
|
|
|
})).then(() => data);
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function cacheItemExpired(item) {
|
|
|
|
return !item || !item.date || Date.now() - item.date > CACHE_DURATION;
|
2017-12-10 07:08:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function cleanupCache() {
|
2018-07-05 12:45:31 +00:00
|
|
|
chromeLocal.remove(CACHE_CLEANUP_NEEDED);
|
|
|
|
if (chrome.storage.local.getBytesInUse) {
|
2017-12-11 02:20:59 +00:00
|
|
|
chrome.storage.local.getBytesInUse(null, size => {
|
|
|
|
if (size > CACHE_SIZE) {
|
|
|
|
chrome.storage.local.get(null, cleanupCacheInternal);
|
2017-12-10 07:08:39 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
ignoreChromeError();
|
|
|
|
});
|
2018-07-05 12:45:31 +00:00
|
|
|
} else {
|
|
|
|
chrome.storage.local.get(null, cleanupCacheInternal);
|
2017-12-11 02:20:59 +00:00
|
|
|
}
|
2017-12-10 07:08:39 +00:00
|
|
|
}
|
2017-12-11 02:20:59 +00:00
|
|
|
|
|
|
|
function cleanupCacheInternal(storage) {
|
|
|
|
const sortedByTime = Object.keys(storage)
|
|
|
|
.filter(key => key.startsWith(CACHE_PREFIX))
|
|
|
|
.map(key => Object.assign(storage[key], {key}))
|
|
|
|
.sort((a, b) => a.date - b.date);
|
|
|
|
const someExpired = cacheItemExpired(sortedByTime[0]);
|
|
|
|
const expired = someExpired ? sortedByTime.filter(cacheItemExpired) :
|
|
|
|
sortedByTime.slice(0, sortedByTime.length / 2);
|
|
|
|
const toRemove = expired.length ? expired : sortedByTime;
|
|
|
|
if (toRemove.length) {
|
|
|
|
chrome.storage.local.remove(toRemove.map(item => item.key), ignoreChromeError);
|
|
|
|
}
|
|
|
|
ignoreChromeError();
|
|
|
|
}
|
|
|
|
|
2018-07-04 12:03:54 +00:00
|
|
|
//endregion
|
2018-12-10 13:14:43 +00:00
|
|
|
//region USO referrer spoofing
|
|
|
|
|
|
|
|
function downloadFromUSO(url) {
|
|
|
|
const requestId = getRandomId();
|
|
|
|
xhrSpoofIds.add(requestId);
|
|
|
|
xhrSpoofStart();
|
|
|
|
return download(url, {
|
|
|
|
body: null,
|
|
|
|
responseType: 'json',
|
2020-06-29 16:16:44 +00:00
|
|
|
timeout: 60e3,
|
2018-12-10 13:14:43 +00:00
|
|
|
headers: {
|
|
|
|
'Referrer-Policy': 'origin-when-cross-origin',
|
|
|
|
[xhrSpoofTelltale]: requestId,
|
2018-07-04 12:03:54 +00:00
|
|
|
}
|
2018-12-10 13:14:43 +00:00
|
|
|
}).then(data => {
|
|
|
|
xhrSpoofDone(requestId);
|
|
|
|
return data;
|
|
|
|
}).catch(data => {
|
|
|
|
xhrSpoofDone(requestId);
|
|
|
|
return Promise.reject(data);
|
2018-07-04 12:03:54 +00:00
|
|
|
});
|
2018-12-10 13:14:43 +00:00
|
|
|
}
|
2018-07-04 12:03:54 +00:00
|
|
|
|
2018-12-10 13:14:43 +00:00
|
|
|
function xhrSpoofStart() {
|
|
|
|
if (chrome.webRequest.onBeforeSendHeaders.hasListener(xhrSpoof)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const urls = [API_URL + '*', JSON_URL + '*'];
|
|
|
|
const types = ['xmlhttprequest'];
|
|
|
|
const options = ['blocking', 'requestHeaders'];
|
|
|
|
// spoofing Referer requires extraHeaders in Chrome 72+
|
|
|
|
if (chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS) {
|
|
|
|
options.push(chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS);
|
|
|
|
}
|
|
|
|
chrome.webRequest.onBeforeSendHeaders.addListener(xhrSpoof, {urls, types}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
function xhrSpoofDone(requestId) {
|
|
|
|
xhrSpoofIds.delete(requestId);
|
|
|
|
if (!xhrSpoofIds.size) {
|
|
|
|
chrome.webRequest.onBeforeSendHeaders.removeListener(xhrSpoof);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function xhrSpoof({requestHeaders}) {
|
|
|
|
let referer, hasTelltale;
|
|
|
|
for (let i = requestHeaders.length; --i >= 0;) {
|
|
|
|
const header = requestHeaders[i];
|
|
|
|
if (header.name.toLowerCase() === 'referer') {
|
|
|
|
referer = header;
|
|
|
|
} else if (header.name === xhrSpoofTelltale) {
|
|
|
|
hasTelltale = xhrSpoofIds.has(header.value);
|
|
|
|
requestHeaders.splice(i, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!hasTelltale) {
|
|
|
|
// not our request (unlikely but just in case)
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (referer) {
|
|
|
|
referer.value = BASE_URL;
|
|
|
|
} else {
|
|
|
|
requestHeaders.push({name: 'Referer', value: BASE_URL});
|
|
|
|
}
|
|
|
|
return {requestHeaders};
|
|
|
|
}
|
|
|
|
|
|
|
|
function getRandomId() {
|
|
|
|
return btoa(Math.random()).replace(/[^a-z]/gi, '');
|
2018-07-04 12:03:54 +00:00
|
|
|
}
|
|
|
|
|
2017-12-11 02:20:59 +00:00
|
|
|
//endregion
|
|
|
|
});
|