extra.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 = function (e) {
  224. e.preventDefault();
  225. faviconExtBtn.disabled = true;
  226. fetch(faviconExtBtn.dataset.extensionUrl, {
  227. method: 'POST',
  228. headers: {
  229. 'Content-Type': 'application/json; charset=utf-8'
  230. },
  231. body: JSON.stringify({
  232. '_csrf': context.csrf,
  233. 'extAction': 'query_icon_info',
  234. 'id': +feed_update.dataset.feedId
  235. }),
  236. }).then(resp => {
  237. if (!resp.ok) {
  238. faviconExtBtn.disabled = false;
  239. return Promise.reject(resp);
  240. }
  241. return resp.json();
  242. }).then(json => {
  243. clearUploadedIcon();
  244. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  245. if (resetField) {
  246. resetField.remove();
  247. }
  248. faviconExtBtn.insertAdjacentHTML('afterend', '<input type="hidden" id="extBtn" value="1" data-leave-validation="" />');
  249. resetFavicon.disabled = false;
  250. faviconError.innerHTML = '';
  251. faviconExt.classList.remove('hidden');
  252. extension.dataset.initialExt = extension.innerText;
  253. extension.innerText = json.extName;
  254. favicon.src = json.iconUrl;
  255. });
  256. };
  257. faviconExtBtn.form.onsubmit = async function (e) {
  258. const extChanged = faviconExtBtn.disabled;
  259. const isSubmit = !e.submitter.hasAttribute('formaction');
  260. if (extChanged && isSubmit) {
  261. e.preventDefault();
  262. faviconExtBtn.form.querySelectorAll('[type="submit"]').forEach(el => {
  263. el.disabled = true;
  264. });
  265. await fetch(faviconExtBtn.dataset.extensionUrl, {
  266. method: 'POST',
  267. headers: {
  268. 'Content-Type': 'application/json; charset=utf-8'
  269. },
  270. body: JSON.stringify({
  271. '_csrf': context.csrf,
  272. 'extAction': 'update_icon',
  273. 'id': +feed_update.dataset.feedId
  274. }),
  275. });
  276. faviconExtBtn.form.onsubmit = null;
  277. faviconExtBtn.form.submit();
  278. }
  279. };
  280. }
  281. }
  282. // <slider>
  283. const freshrssSliderLoadEvent = new Event('freshrss:slider-load');
  284. function open_slider_listener(ev) {
  285. if (ev.ctrlKey || ev.shiftKey) {
  286. return;
  287. }
  288. const a = ev.target.closest('.open-slider');
  289. if (a) {
  290. if (!context.ajax_loading) {
  291. context.ajax_loading = true;
  292. const slider = document.getElementById('slider');
  293. const slider_content = document.getElementById('slider-content');
  294. const req = new XMLHttpRequest();
  295. slider_content.innerHTML = '';
  296. slider.classList.add('sliding');
  297. const ahref = a.href + '&ajax=1#slider';
  298. req.open('GET', ahref, true);
  299. req.responseType = 'document';
  300. req.onload = function (e) {
  301. if (this.status === 403) {
  302. // Redirect to reauth page (or fail if session expired)
  303. location.href = a.href;
  304. return;
  305. }
  306. location.href = '#slider'; // close menu/dropdown
  307. document.documentElement.classList.add('slider-active');
  308. slider.classList.add('active');
  309. slider.scrollTop = 0;
  310. slider_content.innerHTML = this.response.body.innerHTML;
  311. data_auto_leave_validation(slider);
  312. init_update_feed();
  313. slider_content.querySelectorAll('form').forEach(function (f) {
  314. f.insertAdjacentHTML('afterbegin', '<input type="hidden" name="slider" value="1" />');
  315. });
  316. context.ajax_loading = false;
  317. slider.dispatchEvent(freshrssSliderLoadEvent);
  318. };
  319. req.send();
  320. return false;
  321. }
  322. }
  323. }
  324. function init_slider(slider) {
  325. window.onclick = open_slider_listener;
  326. document.getElementById('close-slider').addEventListener('click', close_slider_listener);
  327. document.querySelector('#slider .toggle_aside').addEventListener('click', close_slider_listener);
  328. if (slider.children.length > 0) {
  329. slider.dispatchEvent(freshrssSliderLoadEvent);
  330. }
  331. }
  332. function close_slider_listener(ev) {
  333. const slider = document.getElementById('slider');
  334. if (data_leave_validation(slider) || confirm(context.i18n.confirm_exit_slider)) {
  335. slider.querySelectorAll('form').forEach(function (f) { f.reset(); });
  336. document.documentElement.classList.remove('slider-active');
  337. return true;
  338. }
  339. if (ev) {
  340. ev.preventDefault();
  341. }
  342. return false;
  343. }
  344. // </slider>
  345. // overwrites the href attribute from the url input
  346. function updateHref(ev) {
  347. const urlField = document.getElementById(this.getAttribute('data-input'));
  348. const url = urlField.value;
  349. if (url.length > 0) {
  350. this.href = url;
  351. return true;
  352. } else {
  353. urlField.focus();
  354. this.removeAttribute('href');
  355. ev.preventDefault();
  356. return false;
  357. }
  358. }
  359. // set event listener on "show url" buttons
  360. function init_url_observers(parent) {
  361. parent.querySelectorAll('.open-url').forEach(function (btn) {
  362. btn.addEventListener('mouseover', updateHref);
  363. btn.addEventListener('click', updateHref);
  364. });
  365. }
  366. function init_select_observers() {
  367. document.querySelectorAll('.select-change').forEach(function (s) {
  368. s.onchange = function (ev) {
  369. const opt = s.options[s.selectedIndex];
  370. const url = opt.getAttribute('data-url');
  371. if (url) {
  372. s.disabled = true;
  373. s.value = '';
  374. if (s.form) {
  375. s.form.querySelectorAll('[type=submit]').forEach(function (b) {
  376. b.disabled = true;
  377. });
  378. }
  379. location.href = url;
  380. }
  381. };
  382. });
  383. }
  384. /**
  385. * Returns true when no input element is changed, false otherwise.
  386. * When excludeForm is defined, will only report changes outside the specified form.
  387. */
  388. function data_leave_validation(parent, excludeForm = null) {
  389. const ds = parent.querySelectorAll('[data-leave-validation]');
  390. for (let i = ds.length - 1; i >= 0; i--) {
  391. const input = ds[i];
  392. if (excludeForm && excludeForm === input.form) {
  393. continue;
  394. }
  395. if (input.type === 'checkbox' || input.type === 'radio') {
  396. if (input.checked != input.getAttribute('data-leave-validation')) {
  397. return false;
  398. }
  399. } else if (input.value != input.getAttribute('data-leave-validation')) {
  400. return false;
  401. }
  402. }
  403. return true;
  404. }
  405. /**
  406. * Automatically sets the `data-leave-validation` attribute for input, textarea, select elements for a given parent, if it's not set already.
  407. * Ignores elements with the `data-no-leave-validation` attribute set.
  408. */
  409. function data_auto_leave_validation(parent) {
  410. parent.querySelectorAll(`[data-auto-leave-validation] input,
  411. [data-auto-leave-validation] textarea,
  412. [data-auto-leave-validation] select`).forEach(el => {
  413. if (el.dataset.leaveValidation || el.dataset.noLeaveValidation) {
  414. return;
  415. }
  416. if (el.type === 'checkbox' || el.type === 'radio') {
  417. el.dataset.leaveValidation = +el.checked;
  418. } else if (el.type !== 'hidden') {
  419. el.dataset.leaveValidation = el.value;
  420. }
  421. });
  422. }
  423. function init_2stateButton() {
  424. const btns = document.getElementsByClassName('btn-state1');
  425. Array.prototype.forEach.call(btns, function (el) {
  426. el.addEventListener('click', function () {
  427. const btnState2 = document.getElementById(el.dataset.state2Id);
  428. btnState2.classList.add('show');
  429. this.classList.add('hide');
  430. });
  431. });
  432. }
  433. function init_configuration_alert() {
  434. window.onsubmit = function (e) {
  435. window.hasSubmit = data_leave_validation(document.body, e.target);
  436. };
  437. window.onbeforeunload = function (e) {
  438. if (window.hasSubmit) {
  439. return;
  440. }
  441. if (!data_leave_validation(document.body)) {
  442. return false;
  443. }
  444. };
  445. }
  446. function init_details_attributes() {
  447. function toggleRequired(details) {
  448. details.querySelectorAll('[data-required-if-open]').forEach(el => {
  449. if (details.open) {
  450. el.setAttribute('required', 'required');
  451. } else {
  452. el.removeAttribute('required');
  453. }
  454. });
  455. }
  456. document.querySelectorAll('details').forEach(details => {
  457. details.addEventListener('toggle', () => {
  458. toggleRequired(details);
  459. });
  460. toggleRequired(details);
  461. });
  462. }
  463. function init_extra_afterDOM() {
  464. if (!window.context) {
  465. if (window.console) {
  466. console.log('FreshRSS extra waiting for JS…');
  467. }
  468. setTimeout(init_extra_afterDOM, 50);
  469. return;
  470. }
  471. const loginButton = document.querySelector('#loginButton');
  472. if (loginButton) {
  473. loginButton.addEventListener('click', forgetOpenCategories);
  474. }
  475. if (!['normal', 'global', 'reader'].includes(context.current_view)) {
  476. init_crypto_forms();
  477. init_password_observers(document.body);
  478. init_select_observers();
  479. init_configuration_alert();
  480. init_2stateButton();
  481. init_update_feed();
  482. init_details_attributes();
  483. data_auto_leave_validation(document.body);
  484. const slider = document.getElementById('slider');
  485. if (slider) {
  486. slider.addEventListener('freshrss:slider-load', function (e) {
  487. init_password_observers(slider);
  488. });
  489. init_slider(slider);
  490. init_archiving(slider);
  491. init_url_observers(slider);
  492. } else {
  493. init_archiving(document.body);
  494. init_url_observers(document.body);
  495. }
  496. }
  497. if (window.console) {
  498. console.log('FreshRSS extra init done.');
  499. }
  500. }
  501. if (document.readyState && document.readyState !== 'loading') {
  502. init_extra_afterDOM();
  503. } else {
  504. document.addEventListener('DOMContentLoaded', function () {
  505. if (window.console) {
  506. console.log('FreshRSS extra waiting for DOMContentLoaded…');
  507. }
  508. init_extra_afterDOM();
  509. }, false);
  510. }
  511. // @license-end