extra.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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_forms() {
  17. const crypto_forms = document.querySelectorAll('.crypto-form');
  18. if (crypto_forms.length === 0) {
  19. return;
  20. }
  21. if (!(window.bcrypt)) {
  22. if (window.console) {
  23. console.log('FreshRSS waiting for bcrypt.js…');
  24. }
  25. setTimeout(init_crypto_forms, 100);
  26. return;
  27. }
  28. /* globals bcrypt */
  29. crypto_forms.forEach(crypto_form => {
  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. let challenge = crypto_form.querySelector('#challenge');
  36. if (!challenge) {
  37. crypto_form.querySelectorAll('details[data-challenge-if-open]').forEach(el => {
  38. if (el.open && !challenge) {
  39. crypto_form.insertAdjacentHTML('beforeend', '<input type="hidden" id="challenge" name="challenge" />');
  40. challenge = crypto_form.querySelector('#challenge');
  41. }
  42. });
  43. if (!challenge) {
  44. return true;
  45. }
  46. }
  47. e.preventDefault();
  48. if (!submit_button) {
  49. return false;
  50. }
  51. submit_button.disabled = true;
  52. const req = new XMLHttpRequest();
  53. req.open('GET', './?c=javascript&a=nonce&user=' + crypto_form.querySelector('#username').value, true);
  54. req.onerror = function () {
  55. openNotification('Communication error!', 'bad');
  56. submit_button.disabled = false;
  57. };
  58. req.onload = function () {
  59. if (req.status == 200) {
  60. const json = xmlHttpRequestJson(req);
  61. if (!json.salt1 || !json.nonce) {
  62. openNotification('Invalid user!', 'bad');
  63. } else {
  64. try {
  65. const strong = window.Uint32Array && window.crypto && (typeof window.crypto.getRandomValues === 'function');
  66. const s = bcrypt.hashSync(crypto_form.querySelector('.passwordPlain').value, json.salt1);
  67. const c = bcrypt.hashSync(s + json.nonce, strong ? bcrypt.genSaltSync(4) : poormanSalt());
  68. challenge.value = c;
  69. if (!s || !c) {
  70. openNotification('Crypto error!', 'bad');
  71. } else {
  72. crypto_form.removeEventListener('submit', crypto_form.onsubmit);
  73. crypto_form.submit();
  74. }
  75. } catch (ex) {
  76. openNotification('Crypto exception! ' + ex, 'bad');
  77. }
  78. }
  79. } else {
  80. req.onerror();
  81. }
  82. submit_button.disabled = false;
  83. };
  84. req.send();
  85. };
  86. });
  87. }
  88. // </crypto form (Web login)>
  89. // <show password>
  90. function init_display(parent) {
  91. const theme = parent.querySelector('select#theme');
  92. if (!theme) {
  93. return;
  94. }
  95. theme.addEventListener('change', (e) => {
  96. const picked = parent.querySelector('.preview-container.picked');
  97. picked.classList.remove('picked');
  98. parent.querySelector(`[data-theme-preview="${e.target.value}"]`).classList.add('picked');
  99. });
  100. }
  101. function togglePW(btn) {
  102. if (btn.classList.contains('active')) {
  103. hidePW(btn);
  104. } else {
  105. showPW(btn);
  106. }
  107. return false;
  108. }
  109. function showPW(btn) {
  110. const passwordField = btn.previousElementSibling;
  111. passwordField.setAttribute('type', 'text');
  112. btn.classList.add('active');
  113. clearTimeout(btn.timeoutHide);
  114. btn.timeoutHide = setTimeout(function () { hidePW(btn); }, 5000);
  115. return false;
  116. }
  117. function hidePW(btn) {
  118. clearTimeout(btn.timeoutHide);
  119. const passwordField = btn.previousElementSibling;
  120. passwordField.setAttribute('type', 'password');
  121. passwordField.nextElementSibling.classList.remove('active');
  122. return false;
  123. }
  124. function init_password_observers(parent) {
  125. parent.querySelectorAll('.toggle-password').forEach(function (btn) {
  126. btn.onclick = () => togglePW(btn);
  127. });
  128. }
  129. // </show password>
  130. function init_archiving(parent) {
  131. parent.addEventListener('change', function (e) {
  132. if (e.target.id === 'use_default_purge_options') {
  133. parent.querySelectorAll('.archiving').forEach(function (element) {
  134. element.hidden = e.target.checked;
  135. if (!e.target.checked) element.style.visibility = 'visible'; // Help for Edge 44
  136. });
  137. }
  138. });
  139. parent.addEventListener('click', function (e) {
  140. if (e.target.closest('button[type=reset]')) {
  141. const archiving = document.getElementById('use_default_purge_options');
  142. if (archiving) {
  143. parent.querySelectorAll('.archiving').forEach(function (element) {
  144. element.hidden = archiving.getAttribute('data-leave-validation') == 1;
  145. });
  146. }
  147. }
  148. });
  149. }
  150. function init_update_feed() {
  151. const feed_update = document.querySelector('div.post#feed_update');
  152. if (!feed_update) {
  153. return;
  154. }
  155. const faviconUpload = feed_update.querySelector('#favicon-upload');
  156. const resetFavicon = feed_update.querySelector('#reset-favicon');
  157. const faviconError = feed_update.querySelector('#favicon-error');
  158. const faviconExt = feed_update.querySelector('#favicon-ext');
  159. const extension = faviconExt.querySelector('b');
  160. const faviconExtBtn = feed_update.querySelector('#favicon-ext-btn');
  161. const favicon = feed_update.querySelector('.favicon');
  162. function clearUploadedIcon() {
  163. faviconUpload.value = '';
  164. }
  165. function discardIconChange() {
  166. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  167. if (resetField) {
  168. resetField.remove();
  169. }
  170. const extBtn = feed_update.querySelector('input#extBtn');
  171. if (extBtn) {
  172. extBtn.remove();
  173. }
  174. if (faviconExtBtn) {
  175. faviconExtBtn.disabled = false;
  176. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  177. }
  178. if (extension.innerText == '') {
  179. faviconExt.classList.add('hidden');
  180. }
  181. clearUploadedIcon();
  182. favicon.src = favicon.dataset.initialSrc;
  183. const isCustomFavicon = favicon.getAttribute('src') !== favicon.dataset.originalIcon;
  184. resetFavicon.disabled = !isCustomFavicon;
  185. }
  186. faviconUpload.onchange = function () {
  187. if (faviconUpload.files.length === 0) {
  188. return;
  189. }
  190. faviconExt.classList.add('hidden');
  191. if (faviconUpload.files[0].size > context.max_favicon_upload_size) {
  192. faviconError.innerHTML = context.i18n.favicon_size_exceeded;
  193. discardIconChange();
  194. return;
  195. }
  196. if (faviconExtBtn) {
  197. faviconExtBtn.disabled = false;
  198. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  199. }
  200. faviconError.innerHTML = '';
  201. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  202. if (resetField) {
  203. resetField.remove();
  204. }
  205. const extBtn = feed_update.querySelector('input#extBtn');
  206. if (extBtn) {
  207. extBtn.remove();
  208. }
  209. resetFavicon.disabled = false;
  210. favicon.src = URL.createObjectURL(faviconUpload.files[0]);
  211. };
  212. resetFavicon.onclick = function (e) {
  213. e.preventDefault();
  214. if (resetFavicon.disabled) {
  215. return;
  216. }
  217. if (faviconExtBtn) {
  218. faviconExtBtn.disabled = false;
  219. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  220. }
  221. faviconExt.classList.add('hidden');
  222. faviconError.innerHTML = '';
  223. clearUploadedIcon();
  224. resetFavicon.insertAdjacentHTML('afterend', '<input type="hidden" name="resetFavicon" value="1" data-leave-validation="" />');
  225. resetFavicon.disabled = true;
  226. favicon.src = favicon.dataset.originalIcon;
  227. };
  228. feed_update.querySelector('form').addEventListener('reset', () => {
  229. faviconExt.classList.remove('hidden');
  230. faviconError.innerHTML = '';
  231. discardIconChange();
  232. });
  233. if (faviconExtBtn) {
  234. faviconExtBtn.onclick = async function (e) {
  235. e.preventDefault();
  236. faviconExtBtn.disabled = true;
  237. try {
  238. const resp = await fetch(faviconExtBtn.dataset.extensionUrl, {
  239. method: 'POST',
  240. headers: {
  241. 'Accept': 'application/json',
  242. 'Content-Type': 'application/json; charset=UTF-8',
  243. },
  244. body: JSON.stringify({
  245. '_csrf': context.csrf,
  246. 'extAction': 'query_icon_info',
  247. 'id': +feed_update.dataset.feedId
  248. }),
  249. });
  250. if (!resp.ok) {
  251. faviconExtBtn.disabled = false;
  252. throw new Error(`Custom favicons HTTP error ${resp.status}: ${resp.statusText}`);
  253. }
  254. const json = await resp.json();
  255. clearUploadedIcon();
  256. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  257. if (resetField) {
  258. resetField.remove();
  259. }
  260. faviconExtBtn.insertAdjacentHTML('afterend', '<input type="hidden" id="extBtn" value="1" data-leave-validation="" />');
  261. resetFavicon.disabled = false;
  262. faviconError.innerHTML = '';
  263. faviconExt.classList.remove('hidden');
  264. extension.dataset.initialExt = extension.innerText;
  265. extension.innerText = json.extName;
  266. favicon.src = json.iconUrl;
  267. } catch (error) {
  268. faviconExtBtn.disabled = false;
  269. }
  270. };
  271. faviconExtBtn.form.onsubmit = async function (e) {
  272. const extChanged = faviconExtBtn.disabled;
  273. const isSubmit = !e.submitter.hasAttribute('formaction');
  274. if (extChanged && isSubmit) {
  275. e.preventDefault();
  276. faviconExtBtn.form.querySelectorAll('[type="submit"]').forEach(el => {
  277. el.disabled = true;
  278. });
  279. await fetch(faviconExtBtn.dataset.extensionUrl, {
  280. method: 'POST',
  281. headers: {
  282. 'Content-Type': 'application/json; charset=utf-8'
  283. },
  284. body: JSON.stringify({
  285. '_csrf': context.csrf,
  286. 'extAction': 'update_icon',
  287. 'id': +feed_update.dataset.feedId
  288. }),
  289. });
  290. faviconExtBtn.form.onsubmit = null;
  291. faviconExtBtn.form.submit();
  292. }
  293. };
  294. }
  295. }
  296. // <slider>
  297. const freshrssSliderLoadEvent = new Event('freshrss:slider-load');
  298. function open_slider_listener(ev) {
  299. if (ev.ctrlKey || ev.shiftKey) {
  300. return;
  301. }
  302. const a = ev.target.closest('.open-slider');
  303. if (a) {
  304. if (!context.ajax_loading) {
  305. context.ajax_loading = true;
  306. const slider = document.getElementById('slider');
  307. const slider_content = document.getElementById('slider-content');
  308. const req = new XMLHttpRequest();
  309. slider_content.innerHTML = '';
  310. slider.classList.add('sliding');
  311. const ahref = a.href + '&ajax=1#slider';
  312. req.open('GET', ahref, true);
  313. req.responseType = 'document';
  314. req.onload = function (e) {
  315. if (this.status === 403) {
  316. // Redirect to reauth page (or fail if session expired)
  317. location.href = a.href;
  318. return;
  319. }
  320. location.href = '#slider'; // close menu/dropdown
  321. document.documentElement.classList.add('slider-active');
  322. slider.classList.add('active');
  323. slider.scrollTop = 0;
  324. slider_content.innerHTML = this.response.body.innerHTML;
  325. data_auto_leave_validation(slider);
  326. init_update_feed();
  327. slider_content.querySelectorAll('form').forEach(function (f) {
  328. f.insertAdjacentHTML('afterbegin', '<input type="hidden" name="slider" value="1" />');
  329. });
  330. context.ajax_loading = false;
  331. slider.dispatchEvent(freshrssSliderLoadEvent);
  332. };
  333. req.send();
  334. return false;
  335. }
  336. }
  337. }
  338. function init_slider(slider) {
  339. window.onclick = open_slider_listener;
  340. document.getElementById('close-slider').addEventListener('click', close_slider_listener);
  341. document.querySelector('#slider .toggle_aside').addEventListener('click', close_slider_listener);
  342. if (slider.children.length > 0) {
  343. slider.dispatchEvent(freshrssSliderLoadEvent);
  344. }
  345. }
  346. function close_slider_listener(ev) {
  347. const slider = document.getElementById('slider');
  348. if (data_leave_validation(slider) || confirm(context.i18n.confirm_exit_slider)) {
  349. slider.querySelectorAll('form').forEach(function (f) { f.reset(); });
  350. document.documentElement.classList.remove('slider-active');
  351. return true;
  352. }
  353. if (ev) {
  354. ev.preventDefault();
  355. }
  356. return false;
  357. }
  358. // </slider>
  359. // updates href from the input value, with optional prefix/encoding
  360. function updateHref(ev) {
  361. const urlField = document.getElementById(this.getAttribute('data-input'));
  362. const rawUrl = urlField.value;
  363. const prefix = this.getAttribute('data-prefix') || '';
  364. const shouldEncode = this.getAttribute('data-encode') === '1';
  365. const url = prefix + (shouldEncode ? encodeURIComponent(rawUrl) : rawUrl);
  366. if (rawUrl.length > 0) {
  367. this.href = url;
  368. return true;
  369. } else {
  370. urlField.focus();
  371. this.removeAttribute('href');
  372. ev.preventDefault();
  373. return false;
  374. }
  375. }
  376. // set event listener on "show url" buttons
  377. function init_url_observers(parent) {
  378. parent.querySelectorAll('.open-url').forEach(function (btn) {
  379. btn.addEventListener('mouseover', updateHref);
  380. btn.addEventListener('click', updateHref);
  381. });
  382. }
  383. function init_select_observers() {
  384. document.querySelectorAll('.select-change').forEach(function (s) {
  385. s.onchange = function (ev) {
  386. const opt = s.options[s.selectedIndex];
  387. const url = opt.getAttribute('data-url');
  388. if (url) {
  389. s.disabled = true;
  390. s.value = '';
  391. if (s.form) {
  392. s.form.querySelectorAll('[type=submit]').forEach(function (b) {
  393. b.disabled = true;
  394. });
  395. }
  396. location.href = url;
  397. }
  398. };
  399. });
  400. }
  401. /**
  402. * Returns true when no input element is changed, false otherwise.
  403. * When excludeForm is defined, will only report changes outside the specified form.
  404. */
  405. function data_leave_validation(parent, excludeForm = null) {
  406. const ds = parent.querySelectorAll('[data-leave-validation]');
  407. for (let i = ds.length - 1; i >= 0; i--) {
  408. const input = ds[i];
  409. if (excludeForm && excludeForm === input.form) {
  410. continue;
  411. }
  412. if (input.type === 'checkbox' || input.type === 'radio') {
  413. if (input.checked != input.getAttribute('data-leave-validation')) {
  414. return false;
  415. }
  416. } else if (input.value != input.getAttribute('data-leave-validation')) {
  417. return false;
  418. }
  419. }
  420. return true;
  421. }
  422. /**
  423. * Automatically sets the `data-leave-validation` attribute for input, textarea, select elements for a given parent, if it's not set already.
  424. * Ignores elements with the `data-no-leave-validation` attribute set.
  425. */
  426. function data_auto_leave_validation(parent) {
  427. parent.querySelectorAll(`[data-auto-leave-validation] input,
  428. [data-auto-leave-validation] textarea,
  429. [data-auto-leave-validation] select`).forEach(el => {
  430. if (el.dataset.leaveValidation || el.dataset.noLeaveValidation) {
  431. return;
  432. }
  433. if (el.type === 'checkbox' || el.type === 'radio') {
  434. el.dataset.leaveValidation = +el.checked;
  435. } else if (el.type !== 'hidden') {
  436. el.dataset.leaveValidation = el.value;
  437. }
  438. });
  439. }
  440. function init_2stateButton() {
  441. const btns = document.getElementsByClassName('btn-state1');
  442. Array.prototype.forEach.call(btns, function (el) {
  443. el.addEventListener('click', function () {
  444. const btnState2 = document.getElementById(el.dataset.state2Id);
  445. btnState2.classList.add('show');
  446. this.classList.add('hide');
  447. });
  448. });
  449. }
  450. function init_configuration_alert() {
  451. window.onsubmit = function (e) {
  452. window.hasSubmit = data_leave_validation(document.body, e.target);
  453. };
  454. window.onbeforeunload = function (e) {
  455. if (window.hasSubmit) {
  456. return;
  457. }
  458. if (!data_leave_validation(document.body)) {
  459. return false;
  460. }
  461. };
  462. }
  463. function init_details_attributes() {
  464. function toggleRequired(details) {
  465. details.querySelectorAll('[data-required-if-open]').forEach(el => {
  466. if (details.open) {
  467. el.setAttribute('required', 'required');
  468. } else {
  469. el.removeAttribute('required');
  470. }
  471. });
  472. }
  473. document.querySelectorAll('details').forEach(details => {
  474. details.addEventListener('toggle', () => {
  475. toggleRequired(details);
  476. });
  477. toggleRequired(details);
  478. });
  479. }
  480. function init_user_stats() {
  481. const active = new Set();
  482. const queue = [];
  483. const limit = 10; // Ensure not too many concurrent requests
  484. const processQueue = () => {
  485. while (queue.length > 0 && active.size < limit) {
  486. const row = queue.shift();
  487. const promise = (async () => {
  488. row.removeAttribute('data-need-ajax');
  489. try {
  490. const username = row.querySelector('.username').textContent.trim();
  491. const url = '?c=user&a=details&username=' + encodeURIComponent(username) + '&ajax=1';
  492. const response = await fetch(url);
  493. const html = await response.text();
  494. const parser = new DOMParser();
  495. const doc = parser.parseFromString(html, 'text/html');
  496. row.querySelector('.feed-count').innerHTML = doc.querySelector('.feed_count').innerHTML;
  497. row.querySelector('.article-count').innerHTML = doc.querySelector('.article_count').innerHTML;
  498. row.querySelector('.database-size').innerHTML = doc.querySelector('.database_size').innerHTML;
  499. } catch (err) {
  500. console.error('Error fetching user stats', err);
  501. }
  502. })();
  503. promise.finally(() => {
  504. active.delete(promise);
  505. processQueue();
  506. });
  507. active.add(promise);
  508. }
  509. };
  510. // Retrieve user stats when the row becomes visible
  511. const timers = new WeakMap();
  512. const observer = new IntersectionObserver((entries) => {
  513. entries.forEach(entry => {
  514. if (entry.isIntersecting) {
  515. const timer = setTimeout(() => {
  516. // But wait a bit to avoid triggering on fast scrolls
  517. observer.unobserve(entry.target);
  518. queue.push(entry.target);
  519. processQueue();
  520. }, 100);
  521. timers.set(entry.target, timer);
  522. } else {
  523. clearTimeout(timers.get(entry.target));
  524. }
  525. });
  526. });
  527. document.querySelectorAll('tr[data-need-ajax]').forEach(row => observer.observe(row));
  528. }
  529. function init_extra_afterDOM() {
  530. if (!window.context) {
  531. if (window.console) {
  532. console.log('FreshRSS extra waiting for JS…');
  533. }
  534. setTimeout(init_extra_afterDOM, 50);
  535. return;
  536. }
  537. const loginButton = document.querySelector('#loginButton');
  538. if (loginButton) {
  539. loginButton.addEventListener('click', forgetOpenCategories);
  540. }
  541. if (!['normal', 'global', 'reader'].includes(context.current_view)) {
  542. init_crypto_forms();
  543. init_password_observers(document.body);
  544. init_select_observers();
  545. init_configuration_alert();
  546. init_2stateButton();
  547. init_update_feed();
  548. init_details_attributes();
  549. init_user_stats();
  550. data_auto_leave_validation(document.body);
  551. const slider = document.getElementById('slider');
  552. if (slider) {
  553. slider.addEventListener('freshrss:slider-load', function (e) {
  554. init_password_observers(slider);
  555. });
  556. init_slider(slider);
  557. init_archiving(slider);
  558. init_url_observers(slider);
  559. } else {
  560. init_display(document.body);
  561. init_archiving(document.body);
  562. init_url_observers(document.body);
  563. }
  564. }
  565. if (window.console) {
  566. console.log('FreshRSS extra init done.');
  567. }
  568. }
  569. if (document.readyState && document.readyState !== 'loading') {
  570. init_extra_afterDOM();
  571. } else {
  572. document.addEventListener('DOMContentLoaded', function () {
  573. if (window.console) {
  574. console.log('FreshRSS extra waiting for DOMContentLoaded…');
  575. }
  576. init_extra_afterDOM();
  577. }, false);
  578. }
  579. // @license-end