extra.js 15 KB

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