gitea源码

notification.ts 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import {GET} from '../modules/fetch.ts';
  2. import {toggleElem, createElementFromHTML} from '../utils/dom.ts';
  3. import {logoutFromWorker} from '../modules/worker.ts';
  4. const {appSubUrl, notificationSettings, assetVersionEncoded} = window.config;
  5. let notificationSequenceNumber = 0;
  6. async function receiveUpdateCount(event: MessageEvent<{type: string, data: string}>) {
  7. try {
  8. const data = JSON.parse(event.data.data);
  9. for (const count of document.querySelectorAll('.notification_count')) {
  10. count.classList.toggle('tw-hidden', data.Count === 0);
  11. count.textContent = `${data.Count}`;
  12. }
  13. await updateNotificationTable();
  14. } catch (error) {
  15. console.error(error, event);
  16. }
  17. }
  18. export function initNotificationCount() {
  19. if (!document.querySelector('.notification_count')) return;
  20. let usingPeriodicPoller = false;
  21. const startPeriodicPoller = (timeout: number, lastCount?: number) => {
  22. if (timeout <= 0 || !Number.isFinite(timeout)) return;
  23. usingPeriodicPoller = true;
  24. lastCount = lastCount ?? getCurrentCount();
  25. setTimeout(async () => {
  26. await updateNotificationCountWithCallback(startPeriodicPoller, timeout, lastCount);
  27. }, timeout);
  28. };
  29. if (notificationSettings.EventSourceUpdateTime > 0 && window.EventSource && window.SharedWorker) {
  30. // Try to connect to the event source via the shared worker first
  31. const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
  32. worker.addEventListener('error', (event) => {
  33. console.error('worker error', event);
  34. });
  35. worker.port.addEventListener('messageerror', () => {
  36. console.error('unable to deserialize message');
  37. });
  38. worker.port.postMessage({
  39. type: 'start',
  40. url: `${window.location.origin}${appSubUrl}/user/events`,
  41. });
  42. worker.port.addEventListener('message', (event: MessageEvent<{type: string, data: string}>) => {
  43. if (!event.data || !event.data.type) {
  44. console.error('unknown worker message event', event);
  45. return;
  46. }
  47. if (event.data.type === 'notification-count') {
  48. receiveUpdateCount(event); // no await
  49. } else if (event.data.type === 'no-event-source') {
  50. // browser doesn't support EventSource, falling back to periodic poller
  51. if (!usingPeriodicPoller) startPeriodicPoller(notificationSettings.MinTimeout);
  52. } else if (event.data.type === 'error') {
  53. console.error('worker port event error', event.data);
  54. } else if (event.data.type === 'logout') {
  55. if (event.data.data !== 'here') {
  56. return;
  57. }
  58. worker.port.postMessage({
  59. type: 'close',
  60. });
  61. worker.port.close();
  62. logoutFromWorker();
  63. } else if (event.data.type === 'close') {
  64. worker.port.postMessage({
  65. type: 'close',
  66. });
  67. worker.port.close();
  68. }
  69. });
  70. worker.port.addEventListener('error', (e) => {
  71. console.error('worker port error', e);
  72. });
  73. worker.port.start();
  74. window.addEventListener('beforeunload', () => {
  75. worker.port.postMessage({
  76. type: 'close',
  77. });
  78. worker.port.close();
  79. });
  80. return;
  81. }
  82. startPeriodicPoller(notificationSettings.MinTimeout);
  83. }
  84. function getCurrentCount() {
  85. return Number(document.querySelector('.notification_count').textContent ?? '0');
  86. }
  87. async function updateNotificationCountWithCallback(callback: (timeout: number, newCount: number) => void, timeout: number, lastCount: number) {
  88. const currentCount = getCurrentCount();
  89. if (lastCount !== currentCount) {
  90. callback(notificationSettings.MinTimeout, currentCount);
  91. return;
  92. }
  93. const newCount = await updateNotificationCount();
  94. let needsUpdate = false;
  95. if (lastCount !== newCount) {
  96. needsUpdate = true;
  97. timeout = notificationSettings.MinTimeout;
  98. } else if (timeout < notificationSettings.MaxTimeout) {
  99. timeout += notificationSettings.TimeoutStep;
  100. }
  101. callback(timeout, newCount);
  102. if (needsUpdate) {
  103. await updateNotificationTable();
  104. }
  105. }
  106. async function updateNotificationTable() {
  107. let notificationDiv = document.querySelector('#notification_div');
  108. if (notificationDiv) {
  109. try {
  110. const params = new URLSearchParams(window.location.search);
  111. params.set('div-only', 'true');
  112. params.set('sequence-number', String(++notificationSequenceNumber));
  113. const response = await GET(`${appSubUrl}/notifications?${params.toString()}`);
  114. if (!response.ok) {
  115. throw new Error('Failed to fetch notification table');
  116. }
  117. const data = await response.text();
  118. const el = createElementFromHTML(data);
  119. if (parseInt(el.getAttribute('data-sequence-number')) === notificationSequenceNumber) {
  120. notificationDiv.outerHTML = data;
  121. notificationDiv = document.querySelector('#notification_div');
  122. window.htmx.process(notificationDiv); // when using htmx, we must always remember to process the new content changed by us
  123. }
  124. } catch (error) {
  125. console.error(error);
  126. }
  127. }
  128. }
  129. async function updateNotificationCount(): Promise<number> {
  130. try {
  131. const response = await GET(`${appSubUrl}/notifications/new`);
  132. if (!response.ok) {
  133. throw new Error('Failed to fetch notification count');
  134. }
  135. const data = await response.json();
  136. toggleElem('.notification_count', data.new !== 0);
  137. for (const el of document.querySelectorAll('.notification_count')) {
  138. el.textContent = `${data.new}`;
  139. }
  140. return data.new as number;
  141. } catch (error) {
  142. console.error(error);
  143. return 0;
  144. }
  145. }