extra.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0
  2. 'use strict';
  3. /* globals context, openNotification, xmlHttpRequestJson */
  4. // <crypto form (Web login)>
  5. function poormanSalt() { // If crypto.getRandomValues is not available
  6. const base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.0123456789/abcdefghijklmnopqrstuvwxyz';
  7. let text = '$2a$04$';
  8. for (let i = 22; i > 0; i--) {
  9. text += base.charAt(Math.floor(Math.random() * 64));
  10. }
  11. return text;
  12. }
  13. function forgetOpenCategories() {
  14. localStorage.removeItem('FreshRSS_open_categories');
  15. }
  16. function init_crypto_form() {
  17. /* globals bcrypt */
  18. const crypto_form = document.getElementById('crypto-form');
  19. if (!crypto_form) {
  20. return;
  21. }
  22. if (!(window.bcrypt)) {
  23. if (window.console) {
  24. console.log('FreshRSS waiting for bcrypt.js…');
  25. }
  26. setTimeout(init_crypto_form, 100);
  27. return;
  28. }
  29. forgetOpenCategories();
  30. const submit_button = crypto_form.querySelector('[type="submit"]');
  31. if (submit_button) {
  32. submit_button.disabled = false;
  33. }
  34. crypto_form.onsubmit = function (e) {
  35. e.preventDefault();
  36. if (!submit_button) {
  37. return false;
  38. }
  39. submit_button.disabled = true;
  40. const req = new XMLHttpRequest();
  41. req.open('GET', './?c=javascript&a=nonce&user=' + document.getElementById('username').value, true);
  42. req.onerror = function () {
  43. openNotification('Communication error!', 'bad');
  44. submit_button.disabled = false;
  45. };
  46. req.onload = function () {
  47. if (req.status == 200) {
  48. const json = xmlHttpRequestJson(req);
  49. if (!json.salt1 || !json.nonce) {
  50. openNotification('Invalid user!', 'bad');
  51. } else {
  52. try {
  53. const strong = window.Uint32Array && window.crypto && (typeof window.crypto.getRandomValues === 'function');
  54. const s = bcrypt.hashSync(document.getElementById('passwordPlain').value, json.salt1);
  55. const c = bcrypt.hashSync(json.nonce + s, strong ? bcrypt.genSaltSync(4) : poormanSalt());
  56. document.getElementById('challenge').value = c;
  57. if (!s || !c) {
  58. openNotification('Crypto error!', 'bad');
  59. } else {
  60. crypto_form.removeEventListener('submit', crypto_form.onsubmit);
  61. crypto_form.submit();
  62. }
  63. } catch (ex) {
  64. openNotification('Crypto exception! ' + ex, 'bad');
  65. }
  66. }
  67. } else {
  68. req.onerror();
  69. }
  70. submit_button.disabled = false;
  71. };
  72. req.send();
  73. };
  74. }
  75. // </crypto form (Web login)>
  76. // <show password>
  77. let timeoutHide;
  78. function showPW_this() {
  79. const id_passwordField = this.getAttribute('data-toggle');
  80. if (this.classList.contains('active')) {
  81. hidePW(id_passwordField);
  82. } else {
  83. showPW(id_passwordField);
  84. }
  85. return false;
  86. }
  87. function showPW(id_passwordField) {
  88. const passwordField = document.getElementById(id_passwordField);
  89. passwordField.setAttribute('type', 'text');
  90. passwordField.nextElementSibling.classList.add('active');
  91. clearTimeout(timeoutHide);
  92. timeoutHide = setTimeout(function () { hidePW(id_passwordField); }, 5000);
  93. return false;
  94. }
  95. function hidePW(id_passwordField) {
  96. clearTimeout(timeoutHide);
  97. const passwordField = document.getElementById(id_passwordField);
  98. passwordField.setAttribute('type', 'password');
  99. passwordField.nextElementSibling.classList.remove('active');
  100. return false;
  101. }
  102. function init_password_observers(parent) {
  103. parent.querySelectorAll('.toggle-password').forEach(function (btn) {
  104. btn.addEventListener('click', showPW_this);
  105. });
  106. }
  107. // </show password>
  108. function init_archiving(parent) {
  109. parent.addEventListener('change', function (e) {
  110. if (e.target.id === 'use_default_purge_options') {
  111. parent.querySelectorAll('.archiving').forEach(function (element) {
  112. element.hidden = e.target.checked;
  113. if (!e.target.checked) element.style.visibility = 'visible'; // Help for Edge 44
  114. });
  115. }
  116. });
  117. parent.addEventListener('click', function (e) {
  118. if (e.target.closest('button[type=reset]')) {
  119. const archiving = document.getElementById('use_default_purge_options');
  120. if (archiving) {
  121. parent.querySelectorAll('.archiving').forEach(function (element) {
  122. element.hidden = archiving.getAttribute('data-leave-validation') == 1;
  123. });
  124. }
  125. }
  126. });
  127. }
  128. function init_update_feed() {
  129. const feed_update = document.querySelector('div.post#feed_update');
  130. if (!feed_update) {
  131. return;
  132. }
  133. const faviconUpload = feed_update.querySelector('#favicon-upload');
  134. const resetFavicon = feed_update.querySelector('#reset-favicon');
  135. const faviconError = feed_update.querySelector('#favicon-error');
  136. const faviconExt = feed_update.querySelector('#favicon-ext');
  137. const extension = faviconExt.querySelector('b');
  138. const faviconExtBtn = feed_update.querySelector('#favicon-ext-btn');
  139. const favicon = feed_update.querySelector('.favicon');
  140. function clearUploadedIcon() {
  141. faviconUpload.value = '';
  142. }
  143. function discardIconChange() {
  144. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  145. if (resetField) {
  146. resetField.remove();
  147. }
  148. if (faviconExtBtn) {
  149. faviconExtBtn.disabled = false;
  150. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  151. }
  152. if (extension.innerText == '') {
  153. faviconExt.classList.add('hidden');
  154. }
  155. clearUploadedIcon();
  156. favicon.src = favicon.dataset.initialSrc;
  157. const isCustomFavicon = favicon.getAttribute('src') !== favicon.dataset.originalIcon;
  158. resetFavicon.disabled = !isCustomFavicon;
  159. }
  160. faviconUpload.onchange = function () {
  161. if (faviconUpload.files.length === 0) {
  162. return;
  163. }
  164. faviconExt.classList.add('hidden');
  165. if (faviconUpload.files[0].size > context.max_favicon_upload_size) {
  166. faviconError.innerHTML = context.i18n.favicon_size_exceeded;
  167. discardIconChange();
  168. return;
  169. }
  170. if (faviconExtBtn) {
  171. faviconExtBtn.disabled = false;
  172. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  173. }
  174. faviconError.innerHTML = '';
  175. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  176. if (resetField) {
  177. resetField.remove();
  178. }
  179. resetFavicon.disabled = false;
  180. favicon.src = URL.createObjectURL(faviconUpload.files[0]);
  181. };
  182. resetFavicon.onclick = function (e) {
  183. e.preventDefault();
  184. if (resetFavicon.disabled) {
  185. return;
  186. }
  187. if (faviconExtBtn) {
  188. faviconExtBtn.disabled = false;
  189. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  190. }
  191. faviconExt.classList.add('hidden');
  192. faviconError.innerHTML = '';
  193. clearUploadedIcon();
  194. resetFavicon.insertAdjacentHTML('afterend', '<input type="hidden" name="resetFavicon" value="1" />');
  195. resetFavicon.disabled = true;
  196. favicon.src = favicon.dataset.originalIcon;
  197. };
  198. // Discard the icon change when the "Cancel" button is clicked
  199. feed_update.querySelectorAll('[type="reset"]').forEach(cancelBtn => {
  200. cancelBtn.addEventListener('click', () => {
  201. faviconExt.classList.remove('hidden');
  202. faviconError.innerHTML = '';
  203. discardIconChange();
  204. });
  205. });
  206. if (faviconExtBtn) {
  207. faviconExtBtn.onclick = function (e) {
  208. e.preventDefault();
  209. faviconExtBtn.disabled = true;
  210. fetch(faviconExtBtn.dataset.extensionUrl, {
  211. method: 'POST',
  212. headers: {
  213. 'Content-Type': 'application/json; charset=utf-8'
  214. },
  215. body: JSON.stringify({
  216. '_csrf': context.csrf,
  217. 'extAction': 'query_icon_info',
  218. 'id': +feed_update.dataset.feedId
  219. }),
  220. }).then(resp => {
  221. if (!resp.ok) {
  222. faviconExtBtn.disabled = false;
  223. return Promise.reject(resp);
  224. }
  225. return resp.json();
  226. }).then(json => {
  227. clearUploadedIcon();
  228. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  229. if (resetField) {
  230. resetField.remove();
  231. }
  232. resetFavicon.disabled = false;
  233. faviconError.innerHTML = '';
  234. faviconExt.classList.remove('hidden');
  235. extension.dataset.initialExt = extension.innerText;
  236. extension.innerText = json.extName;
  237. favicon.src = json.iconUrl;
  238. });
  239. };
  240. faviconExtBtn.form.onsubmit = async function (e) {
  241. const extChanged = faviconExtBtn.disabled;
  242. const isSubmit = !e.submitter.hasAttribute('formaction');
  243. if (extChanged && isSubmit) {
  244. e.preventDefault();
  245. faviconExtBtn.form.querySelectorAll('[type="submit"]').forEach(el => {
  246. el.disabled = true;
  247. });
  248. await fetch(faviconExtBtn.dataset.extensionUrl, {
  249. method: 'POST',
  250. headers: {
  251. 'Content-Type': 'application/json; charset=utf-8'
  252. },
  253. body: JSON.stringify({
  254. '_csrf': context.csrf,
  255. 'extAction': 'update_icon',
  256. 'id': +feed_update.dataset.feedId
  257. }),
  258. });
  259. faviconExtBtn.form.onsubmit = null;
  260. faviconExtBtn.form.submit();
  261. }
  262. };
  263. }
  264. }
  265. // <slider>
  266. const freshrssSliderLoadEvent = new Event('freshrss:slider-load');
  267. function open_slider_listener(ev) {
  268. if (ev.ctrlKey || ev.shiftKey) {
  269. return;
  270. }
  271. const a = ev.target.closest('.open-slider');
  272. if (a) {
  273. if (!context.ajax_loading) {
  274. context.ajax_loading = true;
  275. const slider = document.getElementById('slider');
  276. const slider_content = document.getElementById('slider-content');
  277. const req = new XMLHttpRequest();
  278. slider_content.innerHTML = '';
  279. slider.classList.add('sliding');
  280. const ahref = a.href + '&ajax=1#slider';
  281. req.open('GET', ahref, true);
  282. req.responseType = 'document';
  283. req.onload = function (e) {
  284. location.href = '#slider'; // close menu/dropdown
  285. document.documentElement.classList.add('slider-active');
  286. slider.classList.add('active');
  287. slider.scrollTop = 0;
  288. slider_content.innerHTML = this.response.body.innerHTML;
  289. init_update_feed();
  290. slider_content.querySelectorAll('form').forEach(function (f) {
  291. f.insertAdjacentHTML('afterbegin', '<input type="hidden" name="slider" value="1" />');
  292. });
  293. context.ajax_loading = false;
  294. slider.dispatchEvent(freshrssSliderLoadEvent);
  295. };
  296. req.send();
  297. return false;
  298. }
  299. }
  300. }
  301. function init_slider(slider) {
  302. window.onclick = open_slider_listener;
  303. document.getElementById('close-slider').addEventListener('click', close_slider_listener);
  304. document.querySelector('#slider .toggle_aside').addEventListener('click', close_slider_listener);
  305. if (slider.children.length > 0) {
  306. slider.dispatchEvent(freshrssSliderLoadEvent);
  307. }
  308. }
  309. function close_slider_listener(ev) {
  310. const slider = document.getElementById('slider');
  311. if (data_leave_validation(slider) || confirm(context.i18n.confirmation_default)) {
  312. slider.querySelectorAll('form').forEach(function (f) { f.reset(); });
  313. document.documentElement.classList.remove('slider-active');
  314. return;
  315. }
  316. ev.preventDefault();
  317. }
  318. // </slider>
  319. // overwrites the href attribute from the url input
  320. function updateHref(ev) {
  321. const urlField = document.getElementById(this.getAttribute('data-input'));
  322. const url = urlField.value;
  323. if (url.length > 0) {
  324. this.href = url;
  325. return true;
  326. } else {
  327. urlField.focus();
  328. this.removeAttribute('href');
  329. ev.preventDefault();
  330. return false;
  331. }
  332. }
  333. // set event listener on "show url" buttons
  334. function init_url_observers(parent) {
  335. parent.querySelectorAll('.open-url').forEach(function (btn) {
  336. btn.addEventListener('mouseover', updateHref);
  337. btn.addEventListener('click', updateHref);
  338. });
  339. }
  340. function init_select_observers() {
  341. document.querySelectorAll('.select-change').forEach(function (s) {
  342. s.onchange = function (ev) {
  343. const opt = s.options[s.selectedIndex];
  344. const url = opt.getAttribute('data-url');
  345. if (url) {
  346. s.disabled = true;
  347. s.value = '';
  348. if (s.form) {
  349. s.form.querySelectorAll('[type=submit]').forEach(function (b) {
  350. b.disabled = true;
  351. });
  352. }
  353. location.href = url;
  354. }
  355. };
  356. });
  357. }
  358. /**
  359. * Returns true when no input element is changed, false otherwise.
  360. * When excludeForm is defined, will only report changes outside the specified form.
  361. */
  362. function data_leave_validation(parent, excludeForm = null) {
  363. const ds = parent.querySelectorAll('[data-leave-validation]');
  364. for (let i = ds.length - 1; i >= 0; i--) {
  365. const input = ds[i];
  366. if (excludeForm && excludeForm === input.form) {
  367. continue;
  368. }
  369. if (input.type === 'checkbox' || input.type === 'radio') {
  370. if (input.checked != input.getAttribute('data-leave-validation')) {
  371. return false;
  372. }
  373. } else if (input.value != input.getAttribute('data-leave-validation')) {
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. function init_2stateButton() {
  380. const btns = document.getElementsByClassName('btn-state1');
  381. Array.prototype.forEach.call(btns, function (el) {
  382. el.addEventListener('click', function () {
  383. const btnState2 = document.getElementById(el.dataset.state2Id);
  384. btnState2.classList.add('show');
  385. this.classList.add('hide');
  386. });
  387. });
  388. }
  389. function init_configuration_alert() {
  390. window.onsubmit = function (e) {
  391. window.hasSubmit = data_leave_validation(document.body, e.target);
  392. };
  393. window.onbeforeunload = function (e) {
  394. if (window.hasSubmit) {
  395. return;
  396. }
  397. if (!data_leave_validation(document.body)) {
  398. return false;
  399. }
  400. };
  401. }
  402. function init_extra_afterDOM() {
  403. if (!window.context) {
  404. if (window.console) {
  405. console.log('FreshRSS extra waiting for JS…');
  406. }
  407. setTimeout(init_extra_afterDOM, 50);
  408. return;
  409. }
  410. if (!['normal', 'global', 'reader'].includes(context.current_view)) {
  411. init_crypto_form();
  412. init_password_observers(document.body);
  413. init_select_observers();
  414. init_configuration_alert();
  415. init_2stateButton();
  416. init_update_feed();
  417. const slider = document.getElementById('slider');
  418. if (slider) {
  419. slider.addEventListener('freshrss:slider-load', function (e) {
  420. init_password_observers(slider);
  421. });
  422. init_slider(slider);
  423. init_archiving(slider);
  424. init_url_observers(slider);
  425. } else {
  426. init_archiving(document.body);
  427. init_url_observers(document.body);
  428. }
  429. }
  430. if (window.console) {
  431. console.log('FreshRSS extra init done.');
  432. }
  433. }
  434. if (document.readyState && document.readyState !== 'loading') {
  435. init_extra_afterDOM();
  436. } else {
  437. document.addEventListener('DOMContentLoaded', function () {
  438. if (window.console) {
  439. console.log('FreshRSS extra waiting for DOMContentLoaded…');
  440. }
  441. init_extra_afterDOM();
  442. }, false);
  443. }
  444. // @license-end