Porównaj commity

...

3 Commity

Autor SHA1 Wiadomość Data
Alex Gleason 1fca260dd2
Chats: add pleroma:chat_mention to push types 2020-09-24 22:38:46 -05:00
Alex Gleason f305b2e98e
Push: refactor registerer.js 2020-09-24 22:38:33 -05:00
Alex Gleason e8ea75af73
Webpack: refactor sw.js 2020-09-24 22:35:58 -05:00
7 zmienionych plików z 78 dodań i 169 usunięć

Wyświetl plik

@ -34,22 +34,45 @@ const subscribe = (registration, getState) =>
const unsubscribe = ({ registration, subscription }) =>
subscription ? subscription.unsubscribe().then(() => registration) : registration;
const sendSubscriptionToBackend = (subscription, me) => {
const params = { subscription };
const subscriptionToParams = subscription => {
const sub = subscription.toJSON();
return {
endpoint: sub.endpoint,
keys: sub.keys,
};
};
if (me) {
const data = pushNotificationsSetting.get(me);
if (data) {
params.data = data;
}
}
const sendSubscriptionToBackend = (subscription, getState) => {
const params = {
subscription: subscriptionToParams(subscription),
data: {
// TODO: Make configurable
alerts: {
follow: true,
favourite: true,
reblog: true,
mention: true,
poll: true,
'pleroma:chat_mention': true,
},
},
};
return api().post('/api/web/push_subscriptions', params).then(response => response.data);
return api(getState).post('/api/v1/push/subscription', params)
.then(response => response.data);
};
// Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload
const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype);
// Check that the VAPID public key did not change
const vapidKeyMatches = (subscription, getState) => {
const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString();
const subscriptionServerKey = urlBase64ToUint8Array(getApplicationServerKey(getState)).toString();
return currentServerKey === subscriptionServerKey;
};
export function register() {
return (dispatch, getState) => {
const me = getState().get('me');
@ -66,26 +89,21 @@ export function register() {
.then(({ registration, subscription }) => {
if (subscription !== null) {
// We have a subscription, check if it is still valid
const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString();
const subscriptionServerKey = urlBase64ToUint8Array(getApplicationServerKey(getState)).toString();
const serverEndpoint = getState().getIn(['push_notifications', 'subscription', 'endpoint']);
// If the VAPID public key did not change and the endpoint corresponds
// to the endpoint saved in the backend, the subscription is valid
if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) {
// TODO: Also compare `subscription.endpoint`
if (vapidKeyMatches(subscription, getState)) {
return subscription;
} else {
// Something went wrong, try to subscribe again
return unsubscribe({ registration, subscription }).then(registration => {
return subscribe(registration, getState);
}).then(
subscription => sendSubscriptionToBackend(subscription, me));
subscription => sendSubscriptionToBackend(subscription, getState));
}
}
// No subscription, try to subscribe
return subscribe(registration, getState).then(
subscription => sendSubscriptionToBackend(subscription, me));
subscription => sendSubscriptionToBackend(subscription, getState));
})
.then(subscription => {
// If we got a PushSubscription (and not a subscription object from the backend)
@ -102,6 +120,8 @@ export function register() {
console.warn('Your browser supports Web Push Notifications, but does not seem to implement the VAPID protocol.');
} else if (error.code === 5 && error.name === 'InvalidCharacterError') {
console.error('The VAPID public key seems to be invalid:', getApplicationServerKey(getState));
} else {
console.error(error);
}
// Clear alerts and hide UI settings
@ -124,12 +144,11 @@ export function register() {
export function saveSettings() {
return (_, getState) => {
const state = getState().get('push_notifications');
const subscription = state.get('subscription');
const alerts = state.get('alerts');
const data = { alerts };
const me = getState().get('me');
api().put(`/api/web/push_subscriptions/${subscription.get('id')}`, {
api(getState).put('/api/v1/push/subscription', {
data,
}).then(() => {
if (me) {

Wyświetl plik

@ -5,30 +5,19 @@ import { default as Soapbox, store } from './containers/soapbox';
import React from 'react';
import ReactDOM from 'react-dom';
import ready from './ready';
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
const perf = require('./performance');
function main() {
perf.start('main()');
// if (window.history && history.replaceState) {
// const { pathname, search, hash } = window.location;
// const path = pathname + search + hash;
// if (!(/^\/[$/]/).test(path)) {
// console.log('redirecting you to hell');
// history.replaceState(null, document.title, `${path}`);
// }
// }
ready(() => {
const mountNode = document.getElementById('soapbox');
ReactDOM.render(<Soapbox />, mountNode);
if (process.env.NODE_ENV === 'production') {
// avoid offline in dev mode because it's harder to debug
require('offline-plugin/runtime').install();
store.dispatch(registerPushNotifications.register());
}
OfflinePluginRuntime.install();
store.dispatch(registerPushNotifications.register());
perf.stop('main()');
});
}

Wyświetl plik

@ -11,6 +11,7 @@ describe('push_notifications reducer', () => {
reblog: false,
mention: false,
poll: false,
'pleroma:chat_mention': false,
}),
isSubscribed: false,
browserSupport: false,

Wyświetl plik

@ -1,15 +1,15 @@
import { STORE_HYDRATE } from '../actions/store';
import { SET_BROWSER_SUPPORT, SET_SUBSCRIPTION, CLEAR_SUBSCRIPTION, SET_ALERTS } from '../actions/push_notifications';
import Immutable from 'immutable';
import { Map as ImmutableMap } from 'immutable';
const initialState = Immutable.Map({
const initialState = ImmutableMap({
subscription: null,
alerts: new Immutable.Map({
alerts: ImmutableMap({
follow: false,
favourite: false,
reblog: false,
mention: false,
poll: false,
'pleroma:chat_mention': false,
}),
isSubscribed: false,
browserSupport: false,
@ -17,28 +17,10 @@ const initialState = Immutable.Map({
export default function push_subscriptions(state = initialState, action) {
switch(action.type) {
case STORE_HYDRATE: {
const push_subscription = action.state.get('push_subscription');
if (push_subscription) {
return state
.set('subscription', new Immutable.Map({
id: push_subscription.get('id'),
endpoint: push_subscription.get('endpoint'),
}))
.set('alerts', push_subscription.get('alerts') || initialState.get('alerts'))
.set('isSubscribed', true);
}
return state;
}
case SET_SUBSCRIPTION:
return state
.set('subscription', new Immutable.Map({
id: action.subscription.id,
endpoint: action.subscription.endpoint,
}))
.set('alerts', new Immutable.Map(action.subscription.alerts))
.set('subscription', ImmutableMap(action.subscription))
.set('alerts', ImmutableMap(action.subscription.alerts))
.set('isSubscribed', true);
case SET_BROWSER_SUPPORT:
return state.set('browserSupport', action.value);

Wyświetl plik

@ -1,10 +1,5 @@
// import { freeStorage, storageFreeable } from '../storage/modifier';
import './web_push_notifications';
// function openSystemCache() {
// return caches.open('soapbox-system');
// }
function openWebCache() {
return caches.open('soapbox-web');
}
@ -13,92 +8,12 @@ function fetchRoot() {
return fetch('/', { credentials: 'include', redirect: 'manual' });
}
// const firefox = navigator.userAgent.match(/Firefox\/(\d+)/);
// const invalidOnlyIfCached = firefox && firefox[1] < 60;
// Cause a new version of a registered Service Worker to replace an existing one
// that is already installed, and replace the currently active worker on open pages.
self.addEventListener('install', function(event) {
event.waitUntil(Promise.all([openWebCache(), fetchRoot()]).then(([cache, root]) => cache.put('/', root)));
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', function(event) {
const url = new URL(event.request.url);
if (url.pathname === '/auth/sign_out') {
const asyncResponse = fetch(event.request);
const asyncCache = openWebCache();
event.respondWith(asyncResponse.then(response => {
if (response.ok || response.type === 'opaqueredirect') {
return Promise.all([
asyncCache.then(cache => cache.delete('/')),
indexedDB.deleteDatabase('soapbox'),
]).then(() => response);
}
return response;
}));
} else if (
url.pathname.startsWith('/system') ||
url.pathname.startsWith('/api') ||
url.pathname.startsWith('/settings') ||
url.pathname.startsWith('/media') ||
url.pathname.startsWith('/admin') ||
url.pathname.startsWith('/about') ||
url.pathname.startsWith('/auth') ||
url.pathname.startsWith('/oauth') ||
url.pathname.startsWith('/invites') ||
url.pathname.startsWith('/pghero') ||
url.pathname.startsWith('/sidekiq') ||
url.pathname.startsWith('/filters') ||
url.pathname.startsWith('/tags') ||
url.pathname.startsWith('/emojis') ||
url.pathname.startsWith('/inbox') ||
url.pathname.startsWith('/accounts') ||
url.pathname.startsWith('/user') ||
url.pathname.startsWith('/users') ||
url.pathname.startsWith('/src') ||
url.pathname.startsWith('/public') ||
url.pathname.startsWith('/avatars') ||
url.pathname.startsWith('/authorize_follow') ||
url.pathname.startsWith('/media_proxy') ||
url.pathname.startsWith('/relationships')) {
//non-webapp routes
} else if (url.pathname.startsWith('/')) {
// : TODO : if is /web
const asyncResponse = fetchRoot();
const asyncCache = openWebCache();
event.respondWith(asyncResponse.then(
response => {
const clonedResponse = response.clone();
asyncCache.then(cache => cache.put('/', clonedResponse)).catch();
return response;
},
() => asyncCache.then(cache => cache.match('/'))));
} /* else if (storageFreeable && (ATTACHMENT_HOST ? url.host === ATTACHMENT_HOST : url.pathname.startsWith('/system/'))) {
event.respondWith(openSystemCache().then(cache => {
return cache.match(event.request.url).then(cached => {
if (cached === undefined) {
const asyncResponse = invalidOnlyIfCached && event.request.cache === 'only-if-cached' ?
fetch(event.request, { cache: 'no-cache' }) : fetch(event.request);
return asyncResponse.then(response => {
if (response.ok) {
cache
.put(event.request.url, response.clone())
.catch(()=>{}).then(freeStorage()).catch();
}
return response;
});
}
return cached;
});
}));
} */
});

Wyświetl plik

@ -1,10 +1,11 @@
// Note: You must restart bin/webpack-dev-server for changes to take effect
console.log('Running in development mode'); // eslint-disable-line no-console
const { resolve } = require('path');
const { resolve, join } = require('path');
const merge = require('webpack-merge');
const sharedConfig = require('./shared');
const { settings, output } = require('./configuration');
const OfflinePlugin = require('offline-plugin');
const watchOptions = {};
@ -61,6 +62,24 @@ module.exports = merge(sharedConfig, {
pathinfo: true,
},
plugins: [
new OfflinePlugin({
publicPath: output.publicPath,
caches: {
main: [],
additional: [],
optional: [],
},
ServiceWorker: {
entry: join(__dirname, '../app/soapbox/service_worker/entry.js'),
cacheName: 'soapbox-dev',
output: '../sw.js',
publicPath: '/sw.js',
},
AppCache: false,
}),
],
devServer: {
clientLogLevel: 'none',
compress: settings.dev_server.compress,

Wyświetl plik

@ -1,7 +1,7 @@
// Note: You must restart bin/webpack-dev-server for changes to take effect
console.log('Running in production mode'); // eslint-disable-line no-console
const { URL } = require('url');
const path = require('path');
const merge = require('webpack-merge');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const OfflinePlugin = require('offline-plugin');
@ -10,22 +10,6 @@ const CompressionPlugin = require('compression-webpack-plugin');
const { output } = require('./configuration');
const sharedConfig = require('./shared');
// eslint-disable-next-line no-unused-vars
let attachmentHost;
if (process.env.S3_ENABLED === 'true') {
if (process.env.S3_ALIAS_HOST || process.env.S3_CLOUDFRONT_HOST) {
attachmentHost = process.env.S3_ALIAS_HOST || process.env.S3_CLOUDFRONT_HOST;
} else {
attachmentHost = process.env.S3_HOSTNAME || `s3-${process.env.S3_REGION || 'us-east-1'}.amazonaws.com`;
}
} else if (process.env.SWIFT_ENABLED === 'true') {
const { host } = new URL(process.env.SWIFT_OBJECT_URL);
attachmentHost = host;
} else {
attachmentHost = null;
}
module.exports = merge(sharedConfig, {
mode: 'production',
devtool: 'source-map',
@ -94,13 +78,13 @@ module.exports = merge(sharedConfig, {
'**/*-webfont-*.svg',
'**/*.woff',
],
// ServiceWorker: {
// entry: `imports-loader?ATTACHMENT_HOST=>${encodeURIComponent(JSON.stringify(attachmentHost))}!${encodeURI(path.join(__dirname, '../app/soapbox/service_worker/entry.js'))}`,
// cacheName: 'soapbox',
// output: '../assets/sw.js',
// publicPath: '/sw.js',
// minify: true,
// },
ServiceWorker: {
entry: path.join(__dirname, '../app/soapbox/service_worker/entry.js'),
cacheName: 'soapbox',
output: '../sw.js',
publicPath: '/sw.js',
minify: true,
},
}),
],
});