extra.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. const extBtn = feed_update.querySelector('input#extBtn');
  161. if (extBtn) {
  162. extBtn.remove();
  163. }
  164. if (faviconExtBtn) {
  165. faviconExtBtn.disabled = false;
  166. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  167. }
  168. if (extension.innerText == '') {
  169. faviconExt.classList.add('hidden');
  170. }
  171. clearUploadedIcon();
  172. favicon.src = favicon.dataset.initialSrc;
  173. const isCustomFavicon = favicon.getAttribute('src') !== favicon.dataset.originalIcon;
  174. resetFavicon.disabled = !isCustomFavicon;
  175. }
  176. faviconUpload.onchange = function () {
  177. if (faviconUpload.files.length === 0) {
  178. return;
  179. }
  180. faviconExt.classList.add('hidden');
  181. if (faviconUpload.files[0].size > context.max_favicon_upload_size) {
  182. faviconError.innerHTML = context.i18n.favicon_size_exceeded;
  183. discardIconChange();
  184. return;
  185. }
  186. if (faviconExtBtn) {
  187. faviconExtBtn.disabled = false;
  188. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  189. }
  190. faviconError.innerHTML = '';
  191. const resetField = feed_update.querySelector('input[name="resetFavicon"]');
  192. if (resetField) {
  193. resetField.remove();
  194. }
  195. const extBtn = feed_update.querySelector('input#extBtn');
  196. if (extBtn) {
  197. extBtn.remove();
  198. }
  199. resetFavicon.disabled = false;
  200. favicon.src = URL.createObjectURL(faviconUpload.files[0]);
  201. };
  202. resetFavicon.onclick = function (e) {
  203. e.preventDefault();
  204. if (resetFavicon.disabled) {
  205. return;
  206. }
  207. if (faviconExtBtn) {
  208. faviconExtBtn.disabled = false;
  209. extension.innerText = extension.dataset.initialExt ?? extension.innerText;
  210. }
  211. faviconExt.classList.add('hidden');
  212. faviconError.innerHTML = '';
  213. clearUploadedIcon();
  214. resetFavicon.insertAdjacentHTML('afterend', '<input type="hidden" name="resetFavicon" value="1" data-leave-validation="" />');
  215. resetFavicon.disabled = true;
  216. favicon.src = favicon.dataset.originalIcon;
  217. };
  218. feed_update.querySelector('form').addEventListener('reset', () => {
  219. faviconExt.classList.remove('hidden');
  220. faviconError.innerHTML = '';
  221. discardIconChange();
  222. });
  223. if (faviconExtBtn) {
  224. faviconExtBtn.onclick = function (e) {
  225. e.preventDefault();
  226. faviconExtBtn.disabled = true;
  227. fetch(faviconExtBtn.dataset.extensionUrl, {
  228. method: 'POST',
  229. headers: {
  230. 'Content-Type': 'application/json; charset=utf-8'
  231. },
  232. body: JSON.stringify({
  233. '_csrf': context.csrf,
  234. 'extAction': 'query_icon_info',
  235. 'id': +feed_update.dataset.feedId
  236. }),
  237. }).then(resp => {
  238. if (!resp.ok) {
  239. faviconExtBtn.disabled = false;
  240. return Promise.reject(resp);
  241. }
  242. return resp.json();
  243. }).then(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. });
  257. };
  258. faviconExtBtn.form.onsubmit = async function (e) {
  259. const extChanged = faviconExtBtn.disabled;
  260. const isSubmit = !e.submitter.hasAttribute('formaction');
  261. if (extChanged && isSubmit) {
  262. e.preventDefault();
  263. faviconExtBtn.form.querySelectorAll('[type="submit"]').forEach(el => {
  264. el.disabled = true;
  265. });
  266. await fetch(faviconExtBtn.dataset.extensionUrl, {
  267. method: 'POST',
  268. headers: {
  269. 'Content-Type': 'application/json; charset=utf-8'
  270. },
  271. body: JSON.stringify({
  272. '_csrf': context.csrf,
  273. 'extAction': 'update_icon',
  274. 'id': +feed_update.dataset.feedId
  275. }),
  276. });
  277. faviconExtBtn.form.onsubmit = null;
  278. faviconExtBtn.form.submit();
  279. }
  280. };
  281. }
  282. }
  283. // <slider>
  284. const freshrssSliderLoadEvent = new Event('freshrss:slider-load');
  285. function open_slider_listener(ev) {
  286. if (ev.ctrlKey || ev.shiftKey) {
  287. return;
  288. }
  289. const a = ev.target.closest('.open-slider');
  290. if (a) {
  291. if (!context.ajax_loading) {
  292. context.ajax_loading = true;
  293. const slider = document.getElementById('slider');
  294. const slider_content = document.getElementById('slider-content');
  295. const req = new XMLHttpRequest();
  296. slider_content.innerHTML = '';
  297. slider.classList.add('sliding');
  298. const ahref = a.href + '&ajax=1#slider';
  299. req.open('GET', ahref, true);
  300. req.responseType = 'document';
  301. req.onload = function (e) {
  302. if (this.status === 403) {
  303. // Redirect to reauth page (or fail if session expired)
  304. location.href = a.href;
  305. return;
  306. }
  307. location.href = '#slider'; // close menu/dropdown
  308. document.documentElement.classList.add('slider-active');
  309. slider.classList.add('active');
  310. slider.scrollTop = 0;
  311. slider_content.innerHTML = this.response.body.innerHTML;
  312. data_auto_leave_validation(slider);
  313. init_update_feed();
  314. slider_content.querySelectorAll('form').forEach(function (f) {
  315. f.insertAdjacentHTML('afterbegin', '<input type="hidden" name="slider" value="1" />');
  316. });
  317. context.ajax_loading = false;
  318. slider.dispatchEvent(freshrssSliderLoadEvent);
  319. };
  320. req.send();
  321. return false;
  322. }
  323. }
  324. }
  325. function init_slider(slider) {
  326. window.onclick = open_slider_listener;
  327. document.getElementById('close-slider').addEventListener('click', close_slider_listener);
  328. document.querySelector('#slider .toggle_aside').addEventListener('click', close_slider_listener);
  329. if (slider.children.length > 0) {
  330. slider.dispatchEvent(freshrssSliderLoadEvent);
  331. }
  332. }
  333. function close_slider_listener(ev) {
  334. const slider = document.getElementById('slider');
  335. if (data_leave_validation(slider) || confirm(context.i18n.confirm_exit_slider)) {
  336. slider.querySelectorAll('form').forEach(function (f) { f.reset(); });
  337. document.documentElement.classList.remove('slider-active');
  338. return true;
  339. }
  340. if (ev) {
  341. ev.preventDefault();
  342. }
  343. return false;
  344. }
  345. // </slider>
  346. // overwrites the href attribute from the url input
  347. function updateHref(ev) {
  348. const urlField = document.getElementById(this.getAttribute('data-input'));
  349. const url = urlField.value;
  350. if (url.length > 0) {
  351. this.href = url;
  352. return true;
  353. } else {
  354. urlField.focus();
  355. this.removeAttribute('href');
  356. ev.preventDefault();
  357. return false;
  358. }
  359. }
  360. // set event listener on "show url" buttons
  361. function init_url_observers(parent) {
  362. parent.querySelectorAll('.open-url').forEach(function (btn) {
  363. btn.addEventListener('mouseover', updateHref);
  364. btn.addEventListener('click', updateHref);
  365. });
  366. }
  367. function init_select_observers() {
  368. document.querySelectorAll('.select-change').forEach(function (s) {
  369. s.onchange = function (ev) {
  370. const opt = s.options[s.selectedIndex];
  371. const url = opt.getAttribute('data-url');
  372. if (url) {
  373. s.disabled = true;
  374. s.value = '';
  375. if (s.form) {
  376. s.form.querySelectorAll('[type=submit]').forEach(function (b) {
  377. b.disabled = true;
  378. });
  379. }
  380. location.href = url;
  381. }
  382. };
  383. });
  384. }
  385. /**
  386. * Returns true when no input element is changed, false otherwise.
  387. * When excludeForm is defined, will only report changes outside the specified form.
  388. */
  389. function data_leave_validation(parent, excludeForm = null) {
  390. const ds = parent.querySelectorAll('[data-leave-validation]');
  391. for (let i = ds.length - 1; i >= 0; i--) {
  392. const input = ds[i];
  393. if (excludeForm && excludeForm === input.form) {
  394. continue;
  395. }
  396. if (input.type === 'checkbox' || input.type === 'radio') {
  397. if (input.checked != input.getAttribute('data-leave-validation')) {
  398. return false;
  399. }
  400. } else if (input.value != input.getAttribute('data-leave-validation')) {
  401. return false;
  402. }
  403. }
  404. return true;
  405. }
  406. /**
  407. * Automatically sets the `data-leave-validation` attribute for input, textarea, select elements for a given parent, if it's not set already.
  408. * Ignores elements with the `data-no-leave-validation` attribute set.
  409. */
  410. function data_auto_leave_validation(parent) {
  411. parent.querySelectorAll(`[data-auto-leave-validation] input,
  412. [data-auto-leave-validation] textarea,
  413. [data-auto-leave-validation] select`).forEach(el => {
  414. if (el.dataset.leaveValidation || el.dataset.noLeaveValidation) {
  415. return;
  416. }
  417. if (el.type === 'checkbox' || el.type === 'radio') {
  418. el.dataset.leaveValidation = +el.checked;
  419. } else if (el.type !== 'hidden') {
  420. el.dataset.leaveValidation = el.value;
  421. }
  422. });
  423. }
  424. function init_2stateButton() {
  425. const btns = document.getElementsByClassName('btn-state1');
  426. Array.prototype.forEach.call(btns, function (el) {
  427. el.addEventListener('click', function () {
  428. const btnState2 = document.getElementById(el.dataset.state2Id);
  429. btnState2.classList.add('show');
  430. this.classList.add('hide');
  431. });
  432. });
  433. }
  434. function init_configuration_alert() {
  435. window.onsubmit = function (e) {
  436. window.hasSubmit = data_leave_validation(document.body, e.target);
  437. };
  438. window.onbeforeunload = function (e) {
  439. if (window.hasSubmit) {
  440. return;
  441. }
  442. if (!data_leave_validation(document.body)) {
  443. return false;
  444. }
  445. };
  446. }
  447. function init_extra_afterDOM() {
  448. if (!window.context) {
  449. if (window.console) {
  450. console.log('FreshRSS extra waiting for JS…');
  451. }
  452. setTimeout(init_extra_afterDOM, 50);
  453. return;
  454. }
  455. if (!['normal', 'global', 'reader'].includes(context.current_view)) {
  456. init_crypto_form();
  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