extra.js 15 KB

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