87 lines
3.0 KiB
JavaScript
87 lines
3.0 KiB
JavaScript
(function (root) {
|
|
'use strict';
|
|
|
|
var S = root.AutoMirrorShared;
|
|
var D = root.AutoMirrorDiagnostics;
|
|
|
|
function getCachedHost(rule, callback) {
|
|
var key = S.getCacheKey(rule);
|
|
|
|
chrome.storage.local.get([key], function (items) {
|
|
var cached = items[key];
|
|
var ttlHours = Number(rule.cacheTtlHours);
|
|
var neverExpire = !Number.isFinite(ttlHours) || ttlHours <= 0;
|
|
|
|
if (!cached || !cached.host) {
|
|
D.appendDebugLog('debug', 'cache.miss', { rule: rule.name || rule.id || 'unknown', key: key });
|
|
callback(null);
|
|
return;
|
|
}
|
|
|
|
var cachedHost = S.normalizeHost(cached.host);
|
|
if (!S.matchesRule(rule, cachedHost)) {
|
|
chrome.storage.local.remove(key, function () {
|
|
D.log('Removed cached host outside the current rule/range:', cachedHost, 'rule:', rule.name || rule.id);
|
|
});
|
|
callback(null);
|
|
return;
|
|
}
|
|
|
|
if (!neverExpire) {
|
|
var time = Number(cached.time || 0);
|
|
var ttl = ttlHours * 60 * 60 * 1000;
|
|
|
|
if (!time || Date.now() - time > ttl) {
|
|
D.appendDebugLog('info', 'cache.expired', { rule: rule.name || rule.id || 'unknown', cachedHost: cachedHost, ttlHours: ttlHours });
|
|
callback(null);
|
|
return;
|
|
}
|
|
}
|
|
|
|
D.appendDebugLog('debug', 'cache.hit', { rule: rule.name || rule.id || 'unknown', cachedHost: cachedHost, ttlHours: ttlHours, neverExpire: neverExpire });
|
|
callback(cachedHost);
|
|
});
|
|
}
|
|
|
|
function setCachedHost(rule, host) {
|
|
host = S.normalizeHost(host);
|
|
|
|
if (!S.matchesRule(rule, host)) {
|
|
D.log('Not caching host outside the current rule/range:', host, 'rule:', rule.name || rule.id);
|
|
return;
|
|
}
|
|
|
|
var data = {};
|
|
data[S.getCacheKey(rule)] = {
|
|
host: host,
|
|
time: Date.now()
|
|
};
|
|
|
|
chrome.storage.local.set(data, function () {
|
|
D.appendDebugLog('info', 'cache.set', { rule: rule.name || rule.id || 'unknown', host: host });
|
|
});
|
|
}
|
|
|
|
function clearCachedHostIfMatches(rule, host, reason) {
|
|
var key = S.getCacheKey(rule);
|
|
var failedHost = S.normalizeHost(host);
|
|
|
|
chrome.storage.local.get([key], function (items) {
|
|
var cached = items[key];
|
|
var cachedHost = cached && cached.host ? S.normalizeHost(cached.host) : '';
|
|
|
|
if (!cachedHost || cachedHost !== failedHost) return;
|
|
|
|
chrome.storage.local.remove(key, function () {
|
|
D.log('Cleared cached host:', failedHost, 'reason:', reason || 'host-failed');
|
|
});
|
|
});
|
|
}
|
|
|
|
root.AutoMirrorCache = {
|
|
getCachedHost: getCachedHost,
|
|
setCachedHost: setCachedHost,
|
|
clearCachedHostIfMatches: clearCachedHostIfMatches
|
|
};
|
|
})(typeof globalThis !== 'undefined' ? globalThis : this);
|