_helpers.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. 'use strict';
  2. // Contains only auxiliary methods
  3. // May be included and executed unlimited number of times without any consequences
  4. // Polyfills for IE11
  5. Array.prototype.find = Array.prototype.find || function (condition) {
  6. return this.filter(condition)[0];
  7. };
  8. Array.from = Array.from || function (source) {
  9. return Array.prototype.slice.call(source);
  10. };
  11. NodeList.prototype.forEach = NodeList.prototype.forEach || function (callback) {
  12. Array.from(this).forEach(callback);
  13. };
  14. String.prototype.includes = String.prototype.includes || function (searchString) {
  15. return this.indexOf(searchString) >= 0;
  16. };
  17. String.prototype.startsWith = String.prototype.startsWith || function (prefix) {
  18. return this.substr(0, prefix.length) === prefix;
  19. };
  20. Math.sign = Math.sign || function(x) {
  21. x = +x;
  22. if (!x) return x; // 0 and NaN
  23. return x > 0 ? 1 : -1;
  24. };
  25. if (!window.hasOwnProperty('HTMLDetailsElement') && !window.hasOwnProperty('mockHTMLDetailsElement')) {
  26. window.mockHTMLDetailsElement = true;
  27. const style = 'details:not([open]) > :not(summary) {display: none}';
  28. document.head.appendChild(document.createElement('style')).textContent = style;
  29. addEventListener('click', function (e) {
  30. if (e.target.nodeName !== 'SUMMARY') return;
  31. const details = e.target.parentElement;
  32. if (details.hasAttribute('open'))
  33. details.removeAttribute('open');
  34. else
  35. details.setAttribute('open', '');
  36. });
  37. }
  38. // Monstrous global variable for handy code
  39. // Includes: clamp, xhr, storage.{get,set,remove}
  40. window.helpers = window.helpers || {
  41. /**
  42. * https://en.wikipedia.org/wiki/Clamping_(graphics)
  43. * @param {Number} num Source number
  44. * @param {Number} min Low border
  45. * @param {Number} max High border
  46. * @returns {Number} Clamped value
  47. */
  48. clamp: function (num, min, max) {
  49. if (max < min) {
  50. var t = max; max = min; min = t; // swap max and min
  51. }
  52. if (max < num)
  53. return max;
  54. if (min > num)
  55. return min;
  56. return num;
  57. },
  58. /** @private */
  59. _xhr: function (method, url, options, callbacks) {
  60. const xhr = new XMLHttpRequest();
  61. xhr.open(method, url);
  62. // Default options
  63. xhr.responseType = 'json';
  64. xhr.timeout = 10000;
  65. // Default options redefining
  66. if (options.responseType)
  67. xhr.responseType = options.responseType;
  68. if (options.timeout)
  69. xhr.timeout = options.timeout;
  70. if (method === 'POST')
  71. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  72. // better than onreadystatechange because of 404 codes https://stackoverflow.com/a/36182963
  73. xhr.onloadend = function () {
  74. if (xhr.status === 200) {
  75. if (callbacks.on200) {
  76. // fix for IE11. It doesn't convert response to JSON
  77. if (xhr.responseType === '' && typeof(xhr.response) === 'string')
  78. callbacks.on200(JSON.parse(xhr.response));
  79. else
  80. callbacks.on200(xhr.response);
  81. }
  82. } else {
  83. // handled by onerror
  84. if (xhr.status === 0) return;
  85. if (callbacks.onNon200)
  86. callbacks.onNon200(xhr);
  87. }
  88. };
  89. xhr.ontimeout = function () {
  90. if (callbacks.onTimeout)
  91. callbacks.onTimeout(xhr);
  92. };
  93. xhr.onerror = function () {
  94. if (callbacks.onError)
  95. callbacks.onError(xhr);
  96. };
  97. if (options.payload)
  98. xhr.send(options.payload);
  99. else
  100. xhr.send();
  101. },
  102. /** @private */
  103. _xhrRetry: function(method, url, options, callbacks) {
  104. if (options.retries <= 0) {
  105. console.warn('Failed to pull', options.entity_name);
  106. if (callbacks.onTotalFail)
  107. callbacks.onTotalFail();
  108. return;
  109. }
  110. helpers._xhr(method, url, options, callbacks);
  111. },
  112. /**
  113. * @callback callbackXhrOn200
  114. * @param {Object} response - xhr.response
  115. */
  116. /**
  117. * @callback callbackXhrError
  118. * @param {XMLHttpRequest} xhr
  119. */
  120. /**
  121. * @param {'GET'|'POST'} method - 'GET' or 'POST'
  122. * @param {String} url - URL to send request to
  123. * @param {Object} options - other XHR options
  124. * @param {XMLHttpRequestBodyInit} [options.payload=null] - payload for POST-requests
  125. * @param {'arraybuffer'|'blob'|'document'|'json'|'text'} [options.responseType=json]
  126. * @param {Number} [options.timeout=10000]
  127. * @param {Number} [options.retries=1]
  128. * @param {String} [options.entity_name='unknown'] - string to log
  129. * @param {Number} [options.retry_timeout=1000]
  130. * @param {Object} callbacks - functions to execute on events fired
  131. * @param {callbackXhrOn200} [callbacks.on200]
  132. * @param {callbackXhrError} [callbacks.onNon200]
  133. * @param {callbackXhrError} [callbacks.onTimeout]
  134. * @param {callbackXhrError} [callbacks.onError]
  135. * @param {callbackXhrError} [callbacks.onTotalFail] - if failed after all retries
  136. */
  137. xhr: function(method, url, options, callbacks) {
  138. if (!options.retries || options.retries <= 1) {
  139. helpers._xhr(method, url, options, callbacks);
  140. return;
  141. }
  142. if (!options.entity_name) options.entity_name = 'unknown';
  143. if (!options.retry_timeout) options.retry_timeout = 1000;
  144. const retries_total = options.retries;
  145. let currentTry = 1;
  146. const retry = function () {
  147. console.warn('Pulling ' + options.entity_name + ' failed... ' + (currentTry++) + '/' + retries_total);
  148. setTimeout(function () {
  149. options.retries--;
  150. helpers._xhrRetry(method, url, options, callbacks);
  151. }, options.retry_timeout);
  152. };
  153. // Pack retry() call into error handlers
  154. callbacks._onError = callbacks.onError;
  155. callbacks.onError = function (xhr) {
  156. if (callbacks._onError)
  157. callbacks._onError(xhr);
  158. retry();
  159. };
  160. callbacks._onTimeout = callbacks.onTimeout;
  161. callbacks.onTimeout = function (xhr) {
  162. if (callbacks._onTimeout)
  163. callbacks._onTimeout(xhr);
  164. retry();
  165. };
  166. helpers._xhrRetry(method, url, options, callbacks);
  167. },
  168. /**
  169. * @typedef {Object} invidiousStorage
  170. * @property {(key:String) => Object} get
  171. * @property {(key:String, value:Object)} set
  172. * @property {(key:String)} remove
  173. */
  174. /**
  175. * Universal storage, stores and returns JS objects. Uses inside localStorage or cookies
  176. * @type {invidiousStorage}
  177. */
  178. storage: (function () {
  179. // access to localStorage throws exception in Tor Browser, so try is needed
  180. let localStorageIsUsable = false;
  181. try{localStorageIsUsable = !!localStorage.setItem;}catch(e){}
  182. if (localStorageIsUsable) {
  183. return {
  184. get: function (key) {
  185. let storageItem = localStorage.getItem(key)
  186. if (!storageItem) return;
  187. try {
  188. return JSON.parse(decodeURIComponent(storageItem));
  189. } catch(e) {
  190. // Erase non parsable value
  191. helpers.storage.remove(key);
  192. }
  193. },
  194. set: function (key, value) {
  195. let encoded_value = encodeURIComponent(JSON.stringify(value))
  196. localStorage.setItem(key, encoded_value);
  197. },
  198. remove: function (key) { localStorage.removeItem(key); }
  199. };
  200. }
  201. // TODO: fire 'storage' event for cookies
  202. console.info('Storage: localStorage is disabled or unaccessible. Cookies used as fallback');
  203. return {
  204. get: function (key) {
  205. const cookiePrefix = key + '=';
  206. function findCallback(cookie) {return cookie.startsWith(cookiePrefix);}
  207. const matchedCookie = document.cookie.split('; ').find(findCallback);
  208. if (matchedCookie) {
  209. const cookieBody = matchedCookie.replace(cookiePrefix, '');
  210. if (cookieBody.length === 0) return;
  211. try {
  212. return JSON.parse(decodeURIComponent(cookieBody));
  213. } catch(e) {
  214. // Erase non parsable value
  215. helpers.storage.remove(key);
  216. }
  217. }
  218. },
  219. set: function (key, value) {
  220. const cookie_data = encodeURIComponent(JSON.stringify(value));
  221. // Set expiration in 2 year
  222. const date = new Date();
  223. date.setFullYear(date.getFullYear()+2);
  224. document.cookie = key + '=' + cookie_data + '; expires=' + date.toGMTString();
  225. },
  226. remove: function (key) {
  227. document.cookie = key + '=; Max-Age=0';
  228. }
  229. };
  230. })()
  231. };