extra.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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(json.nonce + s, 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 togglePW(btn) {
  91. if (btn.classList.contains('active')) {
  92. hidePW(btn);
  93. } else {
  94. showPW(btn);
  95. }
  96. return false;
  97. }
  98. function showPW(btn) {
  99. const passwordField = btn.previousElementSibling;
  100. passwordField.setAttribute('type', 'text');
  101. btn.classList.add('active');
  102. clearTimeout(btn.timeoutHide);
  103. btn.timeoutHide = setTimeout(function () { hidePW(btn); }, 5000);
  104. return false;
  105. }
  106. function hidePW(btn) {
  107. clearTimeout(btn.timeoutHide);
  108. const passwordField = btn.previousElementSibling;
  109. passwordField.setAttribute('type', 'password');
  110. passwordField.nextElementSibling.classList.remove('active');
  111. return false;
  112. }
  113. function init_password_observers(parent) {
  114. parent.querySelectorAll('.toggle-password').forEach(function (btn) {
  115. btn.onclick = () => togglePW(btn);
  116. });
  117. }
  118. // </show password>
  119. function init_archiving(parent) {
  120. parent.addEventListener('change', function (e) {
  121. if (e.target.id === 'use_default_purge_options') {
  122. parent.querySelectorAll('.archiving').forEach(function (element) {
  123. element.hidden = e.target.checked;
  124. if (!e.target.checked) element.style.visibility = 'visible'; // Help for Edge 44
  125. });
  126. }
  127. });
  128. parent.addEventListener('click', function (e) {
  129. if (e.target.closest('button[type=reset]')) {
  130. const archiving = document.getElementById('use_default_purge_options');
  131. if (archiving) {
  132. parent.querySelectorAll('.archiving').forEach(function (element) {
  133. element.hidden = archiving.getAttribute('data-leave-validation') == 1;
  134. });
  135. }
  136. }
  137. });
  138. }
  139. function init_update_feed() {
  140. const feed_update = document.querySelector('div.post#feed_update');
  141. if (!feed_update) {
  142. return;
  143. }
  144. const faviconUpload = feed_update.querySelector('#favicon-upload');
  145. const resetFavicon = feed_update.querySelector('#reset-favicon');
  146. const faviconError = feed_update.querySelector('#favicon-error');
  147. const faviconExt = feed_update.querySelector('#favicon-ext');
  148. const extension = faviconExt.querySelector('b');
  149. const faviconExtBtn = feed_update.querySelector('#favicon-ext-btn');
  150. const favicon = feed_update.querySelector('.favicon');
  151. function clearUploadedIcon() {
  152. faviconUpload.value = '';
  153. }
  154. function discardIconChange() {
  155. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  156. if (resetField) {
  157. resetField.remove();
  158. }
  159. const extBtn = feed_update.querySelector('input#extBtn');
  160. if (extBtn) {
  161. extBtn.remove();
  162. }
  163. if (faviconExtBtn) {
  164. faviconExtBtn.disabled = false;
  165. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  166. }
  167. if (extension.innerText == '') {
  168. faviconExt.classList.add('hidden');
  169. }
  170. clearUploadedIcon();
  171. favicon.src = favicon.dataset.initialSrc;
  172. const isCustomFavicon = favicon.getAttribute('src') !== favicon.dataset.originalIcon;
  173. resetFavicon.disabled = !isCustomFavicon;
  174. }
  175. faviconUpload.onchange = function () {
  176. if (faviconUpload.files.length === 0) {
  177. return;
  178. }
  179. faviconExt.classList.add('hidden');
  180. if (faviconUpload.files[0].size > context.max_favicon_upload_size) {
  181. faviconError.innerHTML = context.i18n.favicon_size_exceeded;
  182. discardIconChange();
  183. return;
  184. }
  185. if (faviconExtBtn) {
  186. faviconExtBtn.disabled = false;
  187. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  188. }
  189. faviconError.innerHTML = '';
  190. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  191. if (resetField) {
  192. resetField.remove();
  193. }
  194. const extBtn = feed_update.querySelector('input#extBtn');
  195. if (extBtn) {
  196. extBtn.remove();
  197. }
  198. resetFavicon.disabled = false;
  199. favicon.src = URL.createObjectURL(faviconUpload.files[0]);
  200. };
  201. resetFavicon.onclick = function (e) {
  202. e.preventDefault();
  203. if (resetFavicon.disabled) {
  204. return;
  205. }
  206. if (faviconExtBtn) {
  207. faviconExtBtn.disabled = false;
  208. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  209. }
  210. faviconExt.classList.add('hidden');
  211. faviconError.innerHTML = '';
  212. clearUploadedIcon();
  213. resetFavicon.insertAdjacentHTML('afterend', '<input type="hidden" name="resetFavicon" value="1" data-leave-validation="" />');
  214. resetFavicon.disabled = true;
  215. favicon.src = favicon.dataset.originalIcon;
  216. };
  217. feed_update.querySelector('form').addEventListener('reset', () => {
  218. faviconExt.classList.remove('hidden');
  219. faviconError.innerHTML = '';
  220. discardIconChange();
  221. });
  222. if (faviconExtBtn) {
  223. faviconExtBtn.onclick = async function (e) {
  224. e.preventDefault();
  225. faviconExtBtn.disabled = true;
  226. try {
  227. const resp = await fetch(faviconExtBtn.dataset.extensionUrl, {
  228. method: 'POST',
  229. headers: {
  230. 'Accept': 'application/json',
  231. 'Content-Type': 'application/json; charset=UTF-8',
  232. },
  233. body: JSON.stringify({
  234. '_csrf': context.csrf,
  235. 'extAction': 'query_icon_info',
  236. 'id': +feed_update.dataset.feedId
  237. }),
  238. });
  239. if (!resp.ok) {
  240. faviconExtBtn.disabled = false;
  241. throw new Error(`Custom favicons HTTP error ${resp.status}: ${resp.statusText}`);
  242. }
  243. const json = await resp.json();
  244. clearUploadedIcon();
  245. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  246. if (resetField) {
  247. resetField.remove();
  248. }
  249. faviconExtBtn.insertAdjacentHTML('afterend', '<input type="hidden" id="extBtn" value="1" data-leave-validation="" />');
  250. resetFavicon.disabled = false;
  251. faviconError.innerHTML = '';
  252. faviconExt.classList.remove('hidden');
  253. extension.dataset.initialExt = extension.innerText;
  254. extension.innerText = json.extName;
  255. favicon.src = json.iconUrl;
  256. } catch (error) {
  257. faviconExtBtn.disabled = false;
  258. }
  259. };
  260. faviconExtBtn.form.onsubmit = async function (e) {
  261. const extChanged = faviconExtBtn.disabled;
  262. const isSubmit = !e.submitter.hasAttribute('formaction');
  263. if (extChanged && isSubmit) {
  264. e.preventDefault();
  265. faviconExtBtn.form.querySelectorAll('[type="submit"]').forEach(el => {
  266. el.disabled = true;
  267. });
  268. await fetch(faviconExtBtn.dataset.extensionUrl, {
  269. method: 'POST',
  270. headers: {
  271. 'Content-Type': 'application/json; charset=utf-8'
  272. },
  273. body: JSON.stringify({
  274. '_csrf': context.csrf,
  275. 'extAction': 'update_icon',
  276. 'id': +feed_update.dataset.feedId
  277. }),
  278. });
  279. faviconExtBtn.form.onsubmit = null;
  280. faviconExtBtn.form.submit();
  281. }
  282. };
  283. }
  284. }
  285. // <slider>
  286. const freshrssSliderLoadEvent = new Event('freshrss:slider-load');
  287. function open_slider_listener(ev) {
  288. if (ev.ctrlKey || ev.shiftKey) {
  289. return;
  290. }
  291. const a = ev.target.closest('.open-slider');
  292. if (a) {
  293. if (!context.ajax_loading) {
  294. context.ajax_loading = true;
  295. const slider = document.getElementById('slider');
  296. const slider_content = document.getElementById('slider-content');
  297. const req = new XMLHttpRequest();
  298. slider_content.innerHTML = '';
  299. slider.classList.add('sliding');
  300. const ahref = a.href + '&ajax=1#slider';
  301. req.open('GET', ahref, true);
  302. req.responseType = 'document';
  303. req.onload = function (e) {
  304. if (this.status === 403) {
  305. // Redirect to reauth page (or fail if session expired)
  306. location.href = a.href;
  307. return;
  308. }
  309. location.href = '#slider'; // close menu/dropdown
  310. document.documentElement.classList.add('slider-active');
  311. slider.classList.add('active');
  312. slider.scrollTop = 0;
  313. slider_content.innerHTML = this.response.body.innerHTML;
  314. data_auto_leave_validation(slider);
  315. init_update_feed();
  316. slider_content.querySelectorAll('form').forEach(function (f) {
  317. f.insertAdjacentHTML('afterbegin', '<input type="hidden" name="slider" value="1" />');
  318. });
  319. context.ajax_loading = false;
  320. slider.dispatchEvent(freshrssSliderLoadEvent);
  321. };
  322. req.send();
  323. return false;
  324. }
  325. }
  326. }
  327. function init_slider(slider) {
  328. window.onclick = open_slider_listener;
  329. document.getElementById('close-slider').addEventListener('click', close_slider_listener);
  330. document.querySelector('#slider .toggle_aside').addEventListener('click', close_slider_listener);
  331. if (slider.children.length > 0) {
  332. slider.dispatchEvent(freshrssSliderLoadEvent);
  333. }
  334. }
  335. function close_slider_listener(ev) {
  336. const slider = document.getElementById('slider');
  337. if (data_leave_validation(slider) || confirm(context.i18n.confirm_exit_slider)) {
  338. slider.querySelectorAll('form').forEach(function (f) { f.reset(); });
  339. document.documentElement.classList.remove('slider-active');
  340. return true;
  341. }
  342. if (ev) {
  343. ev.preventDefault();
  344. }
  345. return false;
  346. }
  347. // </slider>
  348. // overwrites the href attribute from the url input
  349. function updateHref(ev) {
  350. const urlField = document.getElementById(this.getAttribute('data-input'));
  351. const url = urlField.value;
  352. if (url.length > 0) {
  353. this.href = url;
  354. return true;
  355. } else {
  356. urlField.focus();
  357. this.removeAttribute('href');
  358. ev.preventDefault();
  359. return false;
  360. }
  361. }
  362. // set event listener on "show url" buttons
  363. function init_url_observers(parent) {
  364. parent.querySelectorAll('.open-url').forEach(function (btn) {
  365. btn.addEventListener('mouseover', updateHref);
  366. btn.addEventListener('click', updateHref);
  367. });
  368. }
  369. function init_select_observers() {
  370. document.querySelectorAll('.select-change').forEach(function (s) {
  371. s.onchange = function (ev) {
  372. const opt = s.options[s.selectedIndex];
  373. const url = opt.getAttribute('data-url');
  374. if (url) {
  375. s.disabled = true;
  376. s.value = '';
  377. if (s.form) {
  378. s.form.querySelectorAll('[type=submit]').forEach(function (b) {
  379. b.disabled = true;
  380. });
  381. }
  382. location.href = url;
  383. }
  384. };
  385. });
  386. }
  387. /**
  388. * Returns true when no input element is changed, false otherwise.
  389. * When excludeForm is defined, will only report changes outside the specified form.
  390. */
  391. function data_leave_validation(parent, excludeForm = null) {
  392. const ds = parent.querySelectorAll('[data-leave-validation]');
  393. for (let i = ds.length - 1; i >= 0; i--) {
  394. const input = ds[i];
  395. if (excludeForm && excludeForm === input.form) {
  396. continue;
  397. }
  398. if (input.type === 'checkbox' || input.type === 'radio') {
  399. if (input.checked != input.getAttribute('data-leave-validation')) {
  400. return false;
  401. }
  402. } else if (input.value != input.getAttribute('data-leave-validation')) {
  403. return false;
  404. }
  405. }
  406. return true;
  407. }
  408. /**
  409. * Automatically sets the `data-leave-validation` attribute for input, textarea, select elements for a given parent, if it's not set already.
  410. * Ignores elements with the `data-no-leave-validation` attribute set.
  411. */
  412. function data_auto_leave_validation(parent) {
  413. parent.querySelectorAll(`[data-auto-leave-validation] input,
  414. [data-auto-leave-validation] textarea,
  415. [data-auto-leave-validation] select`).forEach(el => {
  416. if (el.dataset.leaveValidation || el.dataset.noLeaveValidation) {
  417. return;
  418. }
  419. if (el.type === 'checkbox' || el.type === 'radio') {
  420. el.dataset.leaveValidation = +el.checked;
  421. } else if (el.type !== 'hidden') {
  422. el.dataset.leaveValidation = el.value;
  423. }
  424. });
  425. }
  426. function init_2stateButton() {
  427. const btns = document.getElementsByClassName('btn-state1');
  428. Array.prototype.forEach.call(btns, function (el) {
  429. el.addEventListener('click', function () {
  430. const btnState2 = document.getElementById(el.dataset.state2Id);
  431. btnState2.classList.add('show');
  432. this.classList.add('hide');
  433. });
  434. });
  435. }
  436. function init_configuration_alert() {
  437. window.onsubmit = function (e) {
  438. window.hasSubmit = data_leave_validation(document.body, e.target);
  439. };
  440. window.onbeforeunload = function (e) {
  441. if (window.hasSubmit) {
  442. return;
  443. }
  444. if (!data_leave_validation(document.body)) {
  445. return false;
  446. }
  447. };
  448. }
  449. function init_details_attributes() {
  450. function toggleRequired(details) {
  451. details.querySelectorAll('[data-required-if-open]').forEach(el => {
  452. if (details.open) {
  453. el.setAttribute('required', 'required');
  454. } else {
  455. el.removeAttribute('required');
  456. }
  457. });
  458. }
  459. document.querySelectorAll('details').forEach(details => {
  460. details.addEventListener('toggle', () => {
  461. toggleRequired(details);
  462. });
  463. toggleRequired(details);
  464. });
  465. }
  466. function init_extra_afterDOM() {
  467. if (!window.context) {
  468. if (window.console) {
  469. console.log('FreshRSS extra waiting for JS…');
  470. }
  471. setTimeout(init_extra_afterDOM, 50);
  472. return;
  473. }
  474. const loginButton = document.querySelector('#loginButton');
  475. if (loginButton) {
  476. loginButton.addEventListener('click', forgetOpenCategories);
  477. }
  478. if (!['normal', 'global', 'reader'].includes(context.current_view)) {
  479. init_crypto_forms();
  480. init_password_observers(document.body);
  481. init_select_observers();
  482. init_configuration_alert();
  483. init_2stateButton();
  484. init_update_feed();
  485. init_details_attributes();
  486. data_auto_leave_validation(document.body);
  487. const slider = document.getElementById('slider');
  488. if (slider) {
  489. slider.addEventListener('freshrss:slider-load', function (e) {
  490. init_password_observers(slider);
  491. });
  492. init_slider(slider);
  493. init_archiving(slider);
  494. init_url_observers(slider);
  495. } else {
  496. init_archiving(document.body);
  497. init_url_observers(document.body);
  498. }
  499. }
  500. if (window.console) {
  501. console.log('FreshRSS extra init done.');
  502. }
  503. }
  504. if (document.readyState && document.readyState !== 'loading') {
  505. init_extra_afterDOM();
  506. } else {
  507. document.addEventListener('DOMContentLoaded', function () {
  508. if (window.console) {
  509. console.log('FreshRSS extra waiting for DOMContentLoaded…');
  510. }
  511. init_extra_afterDOM();
  512. }, false);
  513. }
  514. // @license-end