logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

entry.js (2612B)


  1. import { freeStorage } from '../storage/modifier';
  2. import './web_push_notifications';
  3. function openSystemCache() {
  4. return caches.open('mastodon-system');
  5. }
  6. function openWebCache() {
  7. return caches.open('mastodon-web');
  8. }
  9. function fetchRoot() {
  10. return fetch('/web', { credentials: 'include' });
  11. }
  12. // Cause a new version of a registered Service Worker to replace an existing one
  13. // that is already installed, and replace the currently active worker on open pages.
  14. self.addEventListener('install', function(event) {
  15. event.waitUntil(Promise.all([openWebCache(), fetchRoot()]).then(([cache, root]) => cache.put('/web', root)));
  16. });
  17. self.addEventListener('activate', function(event) {
  18. event.waitUntil(self.clients.claim());
  19. });
  20. self.addEventListener('fetch', function(event) {
  21. const url = new URL(event.request.url);
  22. if (url.pathname.startsWith('/web')) {
  23. // we always make /web/login go through
  24. if (url.pathname.startsWith('/web/login')) {
  25. return;
  26. }
  27. const asyncResponse = fetchRoot();
  28. const asyncCache = openWebCache();
  29. event.respondWith(asyncResponse.then(async response => {
  30. // response was redirected - let's actually do the request from the event
  31. // and return its response
  32. if (response.redirected || response.type === 'opaqueredirect') {
  33. return await fetch(event.request);
  34. }
  35. if (response.ok) {
  36. const cache = await asyncCache;
  37. await cache.put('/web', response);
  38. return response.clone();
  39. }
  40. throw null;
  41. }).catch(() => asyncCache.then(cache => cache.match('/web'))));
  42. } else if (url.pathname === '/auth/sign_out') {
  43. const asyncResponse = fetch(event.request);
  44. const asyncCache = openWebCache();
  45. event.respondWith(asyncResponse.then(async response => {
  46. if (response.ok || response.type === 'opaqueredirect') {
  47. await Promise.all([
  48. asyncCache.then(cache => cache.delete('/web')),
  49. indexedDB.deleteDatabase('mastodon'),
  50. ]);
  51. }
  52. return response;
  53. }));
  54. } else if (process.env.CDN_HOST ? url.host === process.env.CDN_HOST : url.pathname.startsWith('/system/')) {
  55. event.respondWith(openSystemCache().then(async cache => {
  56. const cached = await cache.match(event.request.url);
  57. if (cached === undefined) {
  58. const fetched = await fetch(event.request);
  59. if (fetched.ok) {
  60. try {
  61. await cache.put(event.request.url, fetched.clone());
  62. } finally {
  63. freeStorage();
  64. }
  65. }
  66. return fetched;
  67. }
  68. return cached;
  69. }));
  70. }
  71. });