assets.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /*******************************************************************************
  2. ηMatrix - a browser extension to black/white list requests.
  3. Copyright (C) 2013-2019 Raymond Hill
  4. Copyright (C) 2019 Alessio Vanni
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see {http://www.gnu.org/licenses/}.
  15. Home: https://libregit.org/heckyel/ematrix
  16. uMatrix Home: https://github.com/gorhill/uMatrix
  17. */
  18. 'use strict';
  19. /******************************************************************************/
  20. ηMatrix.assets = (function() {
  21. let api = {};
  22. let observers = [];
  23. let externalPathRegex = /^(?:[a-z-]+):\/\//;
  24. let connectionError = vAPI.i18n('errorCantConnectTo');
  25. let notifyObservers = function (topic, details) {
  26. let result;
  27. for (let i=0; i<observers.length; ++i) {
  28. result = observers[i](topic, details);
  29. }
  30. return result;
  31. }
  32. function isEmptyString(s) {
  33. return (typeof s === 'string' && s === '');
  34. }
  35. function noOp() {
  36. return;
  37. }
  38. // Cache Registry
  39. var cacheRegistry = new Object();
  40. let cacheRegistryReady = false;
  41. let cacheRegistryCallbacks = undefined;
  42. let cacheRegistryStart = Date.now();
  43. let saveCacheRegistry = (function () {
  44. let timer;
  45. function save() {
  46. timer = undefined;
  47. vAPI.cacheStorage.set({
  48. assetCacheRegistry: cacheRegistry,
  49. });
  50. }
  51. return function (lazy) {
  52. if (timer !== undefined) {
  53. clearTimeout(timer);
  54. }
  55. if (lazy === true) {
  56. timer = vAPI.setTimeout(save, 500);
  57. } else {
  58. save();
  59. }
  60. };
  61. })();
  62. let getCacheRegistry = function (callback) {
  63. if (cacheRegistryReady == true) {
  64. callback(cacheRegistry);
  65. return;
  66. }
  67. if (cacheRegistryCallbacks !== undefined) {
  68. // If it's not undefined it's always an array
  69. //
  70. // eMatrix: this block in particular is probably never
  71. // called: originally, it was used because uMatrix called
  72. // some code in a callback that could wait
  73. //
  74. // While waiting, more elements could've been pushed in
  75. // the array
  76. //
  77. // Since the waiting callback is not used here, any
  78. // further callback are likely to be handled by the
  79. // condition above
  80. // This block is left here just in case
  81. cacheRegistryCallbacks.push(callback);
  82. return;
  83. }
  84. cacheRegistryCallbacks = [callback];
  85. cacheRegistryReady = true;
  86. let onRead = function (bin) {
  87. if (!bin || !bin['assetCacheRegistry']) {
  88. cacheRegistry = {};
  89. } else {
  90. cacheRegistry = bin['assetCacheRegistry'];
  91. }
  92. };
  93. vAPI.cacheStorage.get('assetCacheRegistry', onRead);
  94. let f;
  95. while ((f = cacheRegistryCallbacks.shift())) {
  96. f(cacheRegistry);
  97. }
  98. };
  99. let readCache = function (key, callback) {
  100. let report = function (content, error) {
  101. let details = {
  102. assetKey: key,
  103. content: content,
  104. };
  105. if (error) {
  106. details.error = error;
  107. }
  108. callback(details);
  109. };
  110. let onRead = function (bin) {
  111. if (!bin || !bin[key]) {
  112. report('', 'E_NOTFOUND');
  113. return;
  114. }
  115. let entry = cacheRegistry[key];
  116. if (entry === undefined) {
  117. let onRead2 = function (bin) {
  118. if (!bin || !bin['assetCacheRegistry']) {
  119. cacheRegistry = {};
  120. } else {
  121. cacheRegistry = bin['assetCacheRegistry'];
  122. }
  123. };
  124. vAPI.cacheStorage.get('assetCacheRegistry', onRead2);
  125. entry = cacheRegistry[key];
  126. if (entry === undefined) {
  127. report('', 'E_NOTFOUND');
  128. return;
  129. }
  130. }
  131. entry.readTime = Date.now();
  132. saveCacheRegistry(true);
  133. report(bin[key]);
  134. };
  135. let onReady = function () {
  136. vAPI.cacheStorage.get(key, onRead);
  137. };
  138. getCacheRegistry(onReady);
  139. };
  140. let writeCache = function (key, details, callback) {
  141. let content = '';
  142. if (typeof details === 'string') {
  143. content = details;
  144. } else if (details instanceof Object) {
  145. content = details.content || '';
  146. }
  147. if (content === '') {
  148. removeCache(key, callback);
  149. return;
  150. }
  151. let report = function (content) {
  152. let details = {
  153. assetKey: key,
  154. content: content,
  155. };
  156. if (typeof callback === 'function') {
  157. callback(details);
  158. }
  159. notifyObservers('after-asset-updated', details);
  160. };
  161. let onReady = function () {
  162. let entry = cacheRegistry[key];
  163. if (entry === undefined) {
  164. entry = cacheRegistry[key] = {};
  165. }
  166. entry.writeTime = entry.readTime = Date.now();
  167. if (details instanceof Object && typeof details.url === 'string') {
  168. entry.remoteURL = details.url;
  169. }
  170. let bin = {
  171. assetCacheRegistry: cacheRegistry,
  172. };
  173. bin[key] = content;
  174. vAPI.cacheStorage.set(bin);
  175. report(content);
  176. };
  177. getCacheRegistry(onReady);
  178. };
  179. let cacheRemove = function (pattern, callback) {
  180. let onReady = function (cache) {
  181. let entries = [];
  182. for (let key in cache) {
  183. if (pattern instanceof RegExp && !pattern.test(key)) {
  184. continue;
  185. }
  186. if (typeof pattern === 'string' && key !== pattern) {
  187. continue;
  188. }
  189. entries.push(key);
  190. delete cache[key];
  191. }
  192. if (entries.length !== 0) {
  193. vAPI.cacheStorage.remove(content);
  194. let bin = {
  195. assetCacheRegistry: cache,
  196. };
  197. vAPI.cacheStorage.set(bin);
  198. }
  199. if (typeof callback === 'function') {
  200. callback();
  201. }
  202. for (let i=0; i<entries.length; ++i) {
  203. notifyObservers('after-asset-updated', {
  204. assetKey: entries[i],
  205. });
  206. }
  207. };
  208. getCacheRegistry(onReady);
  209. };
  210. let markDirtyCache = function (pattern, exclude, callback) {
  211. let onReady = function (registry) {
  212. let entry;
  213. let mustSave = false;
  214. for (let key in registry) {
  215. if (pattern instanceof RegExp && pattern.test(key) === false) {
  216. continue;
  217. } else if (typeof pattern === 'string' && key !== pattern) {
  218. continue;
  219. } else if (Array.isArray(pattern)
  220. && pattern.indexOf(key) === -1) {
  221. continue;
  222. }
  223. if (exclude instanceof RegExp && exclude.test(key)) {
  224. continue;
  225. } else if (typeof exclude === 'string' && key === exclude) {
  226. continue;
  227. } else if (Array.isArray(exclude)
  228. && exclude.indexOf(key) !== -1) {
  229. continue;
  230. }
  231. entry = registry[key];
  232. if (!entry.writeTime) {
  233. continue;
  234. }
  235. registry[key].writeTime = 0;
  236. mustSave = true;
  237. }
  238. if (mustSave) {
  239. let bin = {
  240. assetCacheRegistry: registry,
  241. };
  242. vAPI.cacheStorage.set(bin);
  243. }
  244. if (typeof callback === 'function') {
  245. callback();
  246. }
  247. };
  248. if (typeof exclude === 'function') {
  249. callback = exclude;
  250. exclude = undefined;
  251. }
  252. getCacheRegistry(onReady);
  253. };
  254. let removeCache = function (key, callback) {
  255. let onReady = function (cacheRegistry) {
  256. let removedEntries = [];
  257. let removedContent = [];
  258. for (let k in cacheRegistry) {
  259. if (key instanceof RegExp && !key.test(k)) {
  260. continue;
  261. }
  262. if (typeof key === 'string' && k !== key) {
  263. continue;
  264. }
  265. removedEntries.push(k);
  266. removedContent.push(k);
  267. delete cacheRegistry[k];
  268. }
  269. if (removedContent.length > 0) {
  270. vAPI.cacheStorage.remove(removedContent);
  271. let bin = {
  272. assetCacheRegistry: cacheRegistry,
  273. };
  274. vAPI.cacheStorage.set(bin);
  275. }
  276. if (typeof callback === 'function') {
  277. callback();
  278. }
  279. for (let i=0; i<removedEntries.length; ++i) {
  280. notifyObservers('after-asset-updated', {
  281. assetKey: removedEntries[i],
  282. });
  283. }
  284. };
  285. getCacheRegistry(onReady);
  286. };
  287. // Source Registry
  288. var sourceRegistry = Object.create(null);
  289. let sourceRegistryReady = false;
  290. let sourceRegistryCallbacks = undefined;
  291. let saveSourceRegistry = (function () {
  292. let timer;
  293. function save() {
  294. timer = undefined;
  295. vAPI.cacheStorage.set({
  296. assetSourceRegistry: sourceRegistry,
  297. });
  298. }
  299. return function (lazy) {
  300. if (timer !== undefined) {
  301. clearTimeout(timer);
  302. }
  303. if (lazy === true) {
  304. timer = vAPI.setTimeout(save, 500);
  305. } else {
  306. save();
  307. }
  308. };
  309. })();
  310. let registerSource = function (key, details) {
  311. let entry = sourceRegistry[key] || {};
  312. for (let p in details) {
  313. if (details.hasOwnProperty(p) === false) {
  314. continue;
  315. }
  316. if (details[p] !== undefined) {
  317. entry[p] = details[p];
  318. } else {
  319. delete entry[p];
  320. }
  321. }
  322. let contentUrl = details.contentURL;
  323. if (contentUrl) {
  324. if (typeof contentUrl === 'string') {
  325. contentUrl = entry.contentURL = [contentUrl];
  326. } else if (Array.isArray(contentUrl) === false) {
  327. contentUrl = entry.contentURL = [];
  328. }
  329. let remoteCount = 0;
  330. for (let i=0; i<contentUrl.length; ++i) {
  331. if (externalPathRegex.test(contentUrl[i])) {
  332. ++remoteCount;
  333. }
  334. }
  335. entry.hasLocalURL = (remoteCount !== contentUrl.length);
  336. entry.hasRemoteURL = (remoteCount !== 0);
  337. } else {
  338. entry.contentURL = [];
  339. }
  340. if (typeof entry.updateAfter !== 'number') {
  341. entry.updateAfter = 13;
  342. }
  343. if (entry.submitter) {
  344. entry.submitTime = Date.now(); // Detects stale entries
  345. }
  346. sourceRegistry[key] = entry;
  347. };
  348. let unregisterSource = function (key) {
  349. removeCache(key);
  350. delete sourceRegistry[key];
  351. saveSourceRegistry();
  352. };
  353. let updateSourceRegistry = function (string, silent) {
  354. let json;
  355. try {
  356. json = JSON.parse(string);
  357. } catch (e) {
  358. return;
  359. }
  360. for (let key in sourceRegistry) {
  361. if (json[key] === undefined
  362. && sourceRegistry[key].submitter === undefined) {
  363. unregisterSource(key);
  364. }
  365. }
  366. for (let key in json) {
  367. if (sourceRegistry[key] === undefined && !silent) {
  368. notifyObservers('builtin-asset-source-added', {
  369. assetKey: key,
  370. entry: json[key],
  371. });
  372. }
  373. registerSource(key, json[key]);
  374. }
  375. saveSourceRegistry();
  376. };
  377. let getSourceRegistry = function (callback) {
  378. if (sourceRegistryReady === true) {
  379. callback(sourceRegistry);
  380. return;
  381. }
  382. if (sourceRegistryCallbacks !== undefined) {
  383. // If it's not undefined it's always an array
  384. sourceRegistryCallbacks.push(callback);
  385. return;
  386. }
  387. sourceRegistryCallbacks = [callback];
  388. let onReady = function () {
  389. sourceRegistryReady = true;
  390. let f;
  391. while ((f = sourceRegistryCallbacks.shift())) {
  392. f(sourceRegistry);
  393. }
  394. };
  395. let createRegistry = function () {
  396. api.fetchText
  397. (ηMatrix.assetsBootstrapLocation || 'assets/assets.json',
  398. function (details) {
  399. updateSourceRegistry(details.content, true);
  400. onReady();
  401. });
  402. };
  403. let onRead = function (bin) {
  404. if (!bin || !bin.assetSourceRegistry
  405. || Object.keys(bin.assetSourceRegistry).length == 0) {
  406. createRegistry();
  407. return;
  408. }
  409. sourceRegistry = bin.assetSourceRegistry;
  410. onReady();
  411. };
  412. vAPI.cacheStorage.get('assetSourceRegistry', onRead);
  413. };
  414. // Remote
  415. let getRemote = function (key, callback) {
  416. let assetDetails = {};
  417. let contentUrl;
  418. let report = function (content, error) {
  419. let details = {
  420. assetKey: key,
  421. content: content,
  422. };
  423. if (error) {
  424. details.error = assetDetails.lastError = error;
  425. }
  426. callback(details);
  427. };
  428. let tryLoad = function (tries) {
  429. let urls = [];
  430. let tr = (tries === undefined) ? 10 : tries;
  431. if (tr <= 0) {
  432. console.warn('ηMatrix could not load the asset '
  433. +assetDetails.title);
  434. return;
  435. }
  436. if (typeof assetDetails.contentURL === 'string') {
  437. urls = [assetDetails.contentURL];
  438. } else if (Array.isArray(assetDetails.contentURL)) {
  439. urls = assetDetails.contentURL.slice(0);
  440. }
  441. while ((contentUrl = urls.shift())) {
  442. if (externalPathRegex.test(contentUrl)) {
  443. break;
  444. }
  445. }
  446. if (!contentUrl) {
  447. report('', 'E_NOTFOUND');
  448. return;
  449. }
  450. api.fetchText(contentUrl, onRemoteContentLoad, onRemoteContentError,
  451. tr-1);
  452. };
  453. let onRemoteContentLoad = function (details, tries) {
  454. if (isEmptyString(details.content) === true) {
  455. registerSource(key, {
  456. error: {
  457. time: Date.now(),
  458. error: 'No content'
  459. }
  460. });
  461. tryLoad(tries);
  462. }
  463. writeCache(key, {
  464. content: details.content,
  465. url: contentUrl,
  466. });
  467. registerSource(key, {error: undefined});
  468. report(details.content);
  469. };
  470. let onRemoteContentError = function (details, tries) {
  471. let text = detail.statusText;
  472. if (details.statusCode === 0) {
  473. text = 'network error';
  474. }
  475. registerSource(key, {
  476. error: {
  477. time: Date.now(),
  478. error: text,
  479. }
  480. });
  481. tryLoad(tries);
  482. };
  483. let onReady = function (registry) {
  484. assetDetails = registry[key] || {};
  485. tryLoad();
  486. };
  487. getSourceRegistry(onReady);
  488. };
  489. // Updater
  490. let updateStatus = 'stop';
  491. let updateDefaultDelay = 120000;
  492. let updateDelay = updateDefaultDelay;
  493. let updateTimer;
  494. let updated = [];
  495. let updateFetch = new Set();
  496. let updateStart = function () {
  497. updateStatus = 'running';
  498. updateFetch.clear();
  499. updated = [];
  500. notifyObservers('before-assets-updated');
  501. updateNext();
  502. };
  503. let updateNext = function () {
  504. let gcOne = function (key) {
  505. let entry = cacheRegistry[key];
  506. if (entry && entry.readTime < cacheRegistryStart) {
  507. cacheRemove(key);
  508. }
  509. };
  510. let findOne = function () {
  511. let now = Date.now();
  512. let sourceEntry;
  513. let cacheEntry;
  514. for (let key in sourceRegistry) {
  515. sourceEntry = sourceRegistry[key];
  516. if (sourceEntry.hasRemoteURL !== true) {
  517. continue;
  518. }
  519. if (updateFetch.has(key)) {
  520. continue;
  521. }
  522. cacheEntry = cacheRegistry[key];
  523. if (cacheEntry
  524. && (cacheEntry.writeTime
  525. + sourceEntry.updateAfter*86400000) > now) {
  526. continue;
  527. }
  528. if (notifyObservers('before-asset-updated', {assetKey: key})) {
  529. return key;
  530. }
  531. gcOne(key);
  532. }
  533. return undefined;
  534. };
  535. let onUpdate = function (details) {
  536. if (details.content !== '') {
  537. updated.push(details.assetKey);
  538. if (details.assetKey === 'asset.json') {
  539. updateSourceRegistry(details.content);
  540. }
  541. } else {
  542. notifyObservers('asset-update-failed', {
  543. assetKey: details.assetKey,
  544. });
  545. }
  546. if (findOne() !== undefined) {
  547. vAPI.setTimeout(updateNext, updateDelay);
  548. } else {
  549. updateEnd();
  550. }
  551. };
  552. let updateOne = function () {
  553. let key = findOne();
  554. if (key === undefined) {
  555. updateEnd();
  556. return;
  557. }
  558. updateFetch.add(key);
  559. getRemote(key, onUpdate);
  560. };
  561. let onSourceReady = function (registry) {
  562. updateOne();
  563. };
  564. let onCacheReady = function (registry) {
  565. getSourceRegistry(onSourceReady);
  566. };
  567. getCacheRegistry(onCacheReady);
  568. };
  569. let updateEnd = function () {
  570. let keys = updated.slice(0);
  571. updateFetch.clear();
  572. updateStatus = 'stop';
  573. updateDelay = updateDefaultDelay;
  574. notifyObservers('after-asset-updated', {
  575. assetKeys: keys,
  576. });
  577. };
  578. // Assets API
  579. api.addObserver = function (observer) {
  580. if (observers.indexOf(observer) === -1) {
  581. observers.push(observer);
  582. }
  583. };
  584. api.removeObserver = function (observer) {
  585. let pos = observers.indexOf(observer);
  586. if (pos !== -1) {
  587. observers.splice(pos, 1);
  588. }
  589. };
  590. api.fetchText = function (url, onLoad, onError, tries) {
  591. let iurl = externalPathRegex.test(url) ? url : vAPI.getURL(url);
  592. let tr = (tries === undefined) ? 10 : tries;
  593. if (typeof onError !== 'function') {
  594. onError = onLoad;
  595. }
  596. let onResponseReceived = function () {
  597. this.onload = this.onerror = this.ontimeout = null;
  598. let details = {
  599. url: url,
  600. content: '',
  601. // On local files this.status is 0, but the request
  602. // is successful
  603. statusCode: this.status || 200,
  604. statusText: this.statusText || '',
  605. };
  606. if (details.statusCode < 200 || details.statusCode >= 300) {
  607. onError.call(null, details, tr);
  608. return;
  609. }
  610. if (isEmptyString(this.responseText) === true) {
  611. onError.call(null, details, tr);
  612. return;
  613. }
  614. let t = this.responseText.trim();
  615. // Discard HTML as it's probably an error
  616. // (the request expects plain text as a response)
  617. if (t.startsWith('<') && t.endsWith('>')) {
  618. onError.call(null, details, tr);
  619. return;
  620. }
  621. details.content = t;
  622. onLoad.call(null, details, tr);
  623. };
  624. let onErrorReceived = function () {
  625. this.onload = this.onerror = this.ontimeout = null;
  626. ηMatrix.logger.writeOne('', 'error',
  627. connectionError.replace('{{url}}', iurl));
  628. onError.call(null, {
  629. url: url,
  630. content: '',
  631. }, tr);
  632. };
  633. let req = new XMLHttpRequest();
  634. req.open('GET', iurl, true);
  635. req.timeout = 30000;
  636. req.onload = onResponseReceived;
  637. req.onerror = onErrorReceived;
  638. req.ontimeout = onErrorReceived;
  639. req.responseType = 'text';
  640. try {
  641. // This can throw in some cases
  642. req.send();
  643. } catch (e) {
  644. onErrorReceived.call(req);
  645. }
  646. };
  647. api.registerAssetSource = function (key, details) {
  648. getSourceRegistry(function () {
  649. registerSource(key, details);
  650. saveSourceRegistry(true);
  651. });
  652. };
  653. api.unregisterAssetSource = function (key) {
  654. getSourceRegistry(function () {
  655. unregisterSource(key);
  656. saveSourceRegistry(true);
  657. });
  658. };
  659. api.get = function (key, options, callback) {
  660. let cb;
  661. let opt;
  662. if (typeof options === 'function') {
  663. cb = options;
  664. opt = {};
  665. } else if (typeof callback !== 'function') {
  666. cb = noOp;
  667. opt = options;
  668. } else {
  669. cb = callback;
  670. opt = options;
  671. }
  672. let assetDetails = {};
  673. let contentUrl = undefined;
  674. let report = function (content, error) {
  675. let details = {
  676. assetKey: key,
  677. content: content,
  678. };
  679. if (error) {
  680. details.error = assetDetails.error = error;
  681. } else {
  682. assetDetails.error = undefined;
  683. }
  684. cb(details);
  685. };
  686. let onContentNotLoaded = function (details, tries) {
  687. let external;
  688. let urls = [];
  689. let tr = (tries === undefined) ? 10 : tries;
  690. if (tr <= 0) {
  691. console.warn('ηMatrix couldn\'t download the asset '
  692. +assetDetails.title);
  693. return;
  694. }
  695. if (typeof assetDetails.contentURL === 'string') {
  696. urls = [assetDetails.contentURL];
  697. } else if (Array.isArray(assetDetails.contentURL)) {
  698. urls = assetDetails.contentURL.slice(0);
  699. }
  700. while ((contentUrl = urls.shift())) {
  701. external = externalPathRegex.test(contentUrl);
  702. if (external === true && assetDetails.loaded !== true) {
  703. break;
  704. }
  705. if (external === false || assetDetails.hasLocalURL !== true) {
  706. break;
  707. }
  708. }
  709. if (!contentUrl) {
  710. report('', 'E_NOTFOUND');
  711. return;
  712. }
  713. api.fetchText(contentUrl, onContentLoaded, onContentNotLoaded,
  714. tr-1);
  715. };
  716. let onContentLoaded = function (details, tries) {
  717. if (isEmptyString(details.content) === true) {
  718. onContentNotLoaded(undefined, tries);
  719. return;
  720. }
  721. if (externalPathRegex.test(details.url)
  722. && opt.dontCache !== true) {
  723. writeCache(key, {
  724. content: details.content,
  725. url: contentUrl,
  726. });
  727. }
  728. assetDetails.loaded = true;
  729. report(details.content);
  730. };
  731. let onCachedContentLoad = function (details) {
  732. if (details.content !== '') {
  733. report(details.content);
  734. return;
  735. }
  736. let onReady = function (registry) {
  737. assetDetails = registry[key] || {};
  738. onContentNotLoaded();
  739. }
  740. getSourceRegistry(onReady);
  741. };
  742. readCache(key, onCachedContentLoad);
  743. };
  744. api.put = function (key, content, callback) {
  745. writeCache(key, content, callback);
  746. };
  747. api.metadata = function (callback) {
  748. let onSourceReady = function (registry) {
  749. let source = JSON.parse(JSON.stringify(registry));
  750. let cache = cacheRegistry;
  751. let sourceEntry;
  752. let cacheEntry;
  753. let now = Date.now();
  754. let obsoleteAfter;
  755. for (let key in source) {
  756. sourceEntry = source[key];
  757. cacheEntry = cache[key];
  758. if (cacheEntry) {
  759. sourceEntry.cached = true;
  760. sourceEntry.writeTime = cacheEntry.writeTime;
  761. obsoleteAfter = cacheEntry.writeTime
  762. + sourceEntry.updateAfter * 86400000;
  763. sourceEntry.obsolete = obsoleteAfter < now;
  764. sourceEntry.remoteURL = cacheEntry.remoteURL;
  765. } else {
  766. sourceEntry.writeTime = 0;
  767. obsoleteAfter = 0;
  768. sourceEntry.obsolete = true;
  769. }
  770. }
  771. callback(source);
  772. }
  773. let onCacheReady = function () {
  774. getSourceRegistry(onSourceReady);
  775. }
  776. getCacheRegistry(onCacheReady);
  777. };
  778. api.purge = function (pattern, exclude, callback) {
  779. markDirtyCache(pattern, exclude, callback);
  780. };
  781. api.remove = function (pattern, callback) {
  782. cacheRemove(pattern, callback);
  783. };
  784. api.rmrf = function () {
  785. cacheRemove(/./);
  786. };
  787. api.updateStart = function (details) {
  788. let oldDelay = updateDelay;
  789. let newDelay = details.delay || updateDefaultDelay;
  790. updateDelay = Math.min(oldDelay, newDelay);
  791. if (updateStatus === 'running') {
  792. if (newDelay < oldDelay) {
  793. clearTimeout(updateTimer);
  794. updateTimer = vAPI.setTimeout(updateNext, updateDelay);
  795. }
  796. return;
  797. }
  798. updateStart();
  799. };
  800. api.updateStop = function () {
  801. if (updateTimer) {
  802. clearTimeout(updateTimer);
  803. updateTimer = undefined;
  804. }
  805. if (updateStatus === 'running') {
  806. updateEnd();
  807. }
  808. };
  809. return api;
  810. })();
  811. /******************************************************************************/