extra.js 14 KB

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