This commit is contained in:
tamaina
2021-02-10 01:54:07 +09:00
parent c44a29ebb7
commit f95ca164d6
11 changed files with 259 additions and 176 deletions

View File

@@ -1,107 +0,0 @@
/**
* Notification composer of Service Worker
*/
declare var self: ServiceWorkerGlobalScope;
import { getNoteSummary } from '../../misc/get-note-summary';
import getUserName from '../../misc/get-user-name';
export default async function(data, i18n): Promise<[string, NotificationOptions] | null | undefined> {
if (!i18n) {
console.log('no i18n');
return;
}
switch (data.type) {
case 'driveFileCreated': // TODO (Server Side)
return [i18n.t('_notification.fileUploaded'), {
body: data.body.name,
icon: data.body.url,
data
}];
case 'notification':
switch (data.body.type) {
case 'mention':
return [i18n.t('_notification.youGotMention', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl,
data,
actions: [
{
action: 'showUser',
title: 'showUser'
}
]
}];
case 'reply':
return [i18n.t('_notification.youGotReply', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'renote':
return [i18n.t('_notification.youRenoted', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'quote':
return [i18n.t('_notification.youGotQuote', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'reaction':
return [`${data.body.reaction} ${getUserName(data.body.user)}`, {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'pollVote':
return [i18n.t('_notification.youGotPoll', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'follow':
return [i18n.t('_notification.youWereFollowed'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'receiveFollowRequest':
return [i18n.t('_notification.youReceivedFollowRequest'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'followRequestAccepted':
return [i18n.t('_notification.yourFollowRequestAccepted'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'groupInvited':
return [i18n.t('_notification.youWereInvitedToGroup'), {
body: data.body.group.name
}];
default:
return null;
}
case 'unreadMessagingMessage':
if (data.body.groupId === null) {
return [i18n.t('_notification.youGotMessagingMessageFromUser', { name: getUserName(data.body.user) }), {
icon: data.body.user.avatarUrl,
tag: `messaging:user:${data.body.user.id}`
}];
}
return [i18n.t('_notification.youGotMessagingMessageFromGroup', { name: data.body.group.name }), {
icon: data.body.user.avatarUrl,
tag: `messaging:group:${data.body.group.id}`
}];
default:
return null;
}
}

44
src/client/sw/lang.ts Normal file
View File

@@ -0,0 +1,44 @@
/*
* Language manager for SW
*/
declare var self: ServiceWorkerGlobalScope;
import { get, set } from 'idb-keyval';
import { I18n } from '@/scripts/i18n';
class SwLang {
public cacheName = `mk-cache-${_VERSION_}`;
public lang: Promise<string> = get('lang').then(async prelang => {
if (!prelang) return 'en-US';
return prelang;
});
public i18n: I18n<any> | null = null;
public setLang(newLang: string) {
this.i18n = null;
this.lang = Promise.resolve(newLang);
set('lang', newLang);
return this.fetchLocale();
}
public async fetchLocale() {
// Service Workerは何度も起動しそのたびにlocaleを読み込むので、CacheStorageを使う
const localeUrl = `/assets/locales/${await this.lang}.${_VERSION_}.json`;
let localeRes = await caches.match(localeUrl);
if (!localeRes) {
localeRes = await fetch(localeUrl);
const clone = localeRes?.clone();
if (!clone?.clone().ok) return;
caches.open(this.cacheName).then(cache => cache.put(localeUrl, clone));
}
return this.i18n = new I18n(await localeRes.json());
}
}
export const swLang = new SwLang();

View File

@@ -0,0 +1,137 @@
/*
* Notification manager for SW
*/
declare var self: ServiceWorkerGlobalScope;
import { getNoteSummary } from '../../misc/get-note-summary';
import getUserName from '../../misc/get-user-name';
import { swLang } from '@/sw/lang'
class SwNotification {
private queue: any[] = [];
private fetching = false;
public async append(data) {
if (swLang.i18n) {
const n = await this.composeNotification(data);
if (n) return self.registration.showNotification(...n);
} else {
this.queue.push(data);
if (this.fetching == false) {
this.fetching = true;
await swLang.fetchLocale();
this.fetching = false;
const promises = this.queue.map(this.composeNotification).map(n => {
if (!n) return;
return self.registration.showNotification(...n);
})
this.queue = [];
return Promise.all(promises);
}
}
}
private composeNotification(data): [string, NotificationOptions] | null | undefined {
const { i18n } = swLang;
if (!i18n) return;
const { t } = i18n;
switch (data.type) {
case 'driveFileCreated': // TODO (Server Side)
return [t('_notification.fileUploaded'), {
body: data.body.name,
icon: data.body.url,
data
}];
case 'notification':
switch (data.body.type) {
case 'mention':
return [t('_notification.youGotMention', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl,
data,
actions: [
{
action: 'showUser',
title: 'showUser'
}
]
}];
case 'reply':
return [t('_notification.youGotReply', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'renote':
return [t('_notification.youRenoted', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'quote':
return [t('_notification.youGotQuote', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'reaction':
return [`${data.body.reaction} ${getUserName(data.body.user)}`, {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'pollVote':
return [t('_notification.youGotPoll', { name: getUserName(data.body.user) }), {
body: getNoteSummary(data.body.note, i18n.locale),
icon: data.body.user.avatarUrl
}];
case 'follow':
return [t('_notification.youWereFollowed'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'receiveFollowRequest':
return [t('_notification.youReceivedFollowRequest'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'followRequestAccepted':
return [t('_notification.yourFollowRequestAccepted'), {
body: getUserName(data.body.user),
icon: data.body.user.avatarUrl
}];
case 'groupInvited':
return [t('_notification.youWereInvitedToGroup'), {
body: data.body.group.name
}];
default:
return null;
}
case 'unreadMessagingMessage':
if (data.body.groupId === null) {
return [t('_notification.youGotMessagingMessageFromUser', { name: getUserName(data.body.user) }), {
icon: data.body.user.avatarUrl,
tag: `messaging:user:${data.body.user.id}`
}];
}
return [t('_notification.youGotMessagingMessageFromGroup', { name: data.body.group.name }), {
icon: data.body.user.avatarUrl,
tag: `messaging:group:${data.body.group.id}`
}];
default:
return null;
}
}
}
export const swNotification = new SwNotification();

View File

@@ -3,49 +3,13 @@
*/
declare var self: ServiceWorkerGlobalScope;
import { get, set } from 'idb-keyval';
import composeNotification from '@/sw/compose-notification';
import { I18n } from '@/scripts/i18n';
import { get } from 'idb-keyval';
import { swNotification } from '@/sw/notification';
import { swLang } from '@/sw/lang';
//#region Variables
const version = _VERSION_;
const cacheName = `mk-cache-${version}`;
// const cacheName = `mk-cache-${_VERSION_}`;
const apiUrl = `${location.origin}/api/`;
let lang: Promise<string> = get('lang').then(async prelang => {
if (!prelang) return 'en-US';
return prelang;
});
let i18n: I18n<any>;
let pushesPool: any[] = [];
//#endregion
//#region Function: (Re)Load i18n instance
async function fetchLocale() {
//#region localeファイルの読み込み
// Service Workerは何度も起動しそのたびにlocaleを読み込むので、CacheStorageを使う
const localeUrl = `/assets/locales/${await lang}.${version}.json`;
let localeRes = await caches.match(localeUrl);
if (!localeRes) {
localeRes = await fetch(localeUrl);
const clone = localeRes?.clone();
if (!clone?.clone().ok) return;
caches.open(cacheName).then(cache => cache.put(localeUrl, clone));
}
i18n = new I18n(await localeRes.json());
//#endregion
//#region i18nをきちんと読み込んだ後にやりたい処理
for (const data of pushesPool) {
const n = await composeNotification(data, i18n);
if (n) self.registration.showNotification(...n);
}
pushesPool = [];
//#endregion
}
//#endregion
//#region Lifecycle: Install
@@ -60,7 +24,7 @@ self.addEventListener('activate', ev => {
caches.keys()
.then(cacheNames => Promise.all(
cacheNames
.filter((v) => v !== cacheName)
.filter((v) => v !== swLang.cacheName)
.map(name => caches.delete(name))
))
.then(() => self.clients.claim())
@@ -93,11 +57,22 @@ self.addEventListener('push', ev => {
const data = ev.data?.json();
// localeを読み込めておらずi18nがundefinedだった場合はpushesPoolにためておく
if (!i18n) return pushesPool.push(data);
const n = await composeNotification(data, i18n);
if (n) return self.registration.showNotification(...n);
switch (data.type) {
case 'notification':
case 'driveFileCreated':
case 'unreadMessagingMessage':
return swNotification.append(data);
case 'readAllNotifications':
for (const n of await self.registration.getNotifications()) {
n.close();
}
break;
case 'readNotifications':
for (const n of await self.registration.getNotifications()) {
if (data.notificationIds.includes(n.data.body.id)) n.close();
}
break;
}
}));
});
//#endregion
@@ -108,16 +83,18 @@ self.addEventListener('notificationclick', ev => {
const { data } = notification;
const { origin } = location;
const suffix = `?loginId=${data.userId}`;
switch (action) {
case 'showUser':
switch (data.body.type) {
case 'reaction':
self.clients.openWindow(`${origin}/users/${data.body.user.id}`);
self.clients.openWindow(`${origin}/users/${data.body.user.id}${suffix}`);
break;
default:
if ('note' in data.body) {
self.clients.openWindow(`${origin}/notes/${data.body.note.id}`);
self.clients.openWindow(`${origin}/users/${data.body.note.user.id}${suffix}`);
}
}
break;
@@ -128,8 +105,10 @@ self.addEventListener('notificationclick', ev => {
});
self.addEventListener('notificationclose', async ev => {
self.registration.showNotification('notificationclose');
const { notification } = ev;
if (notification.title !== 'notificationclose') {
self.registration.showNotification('notificationclose', { body: `${notification.data.id}` });
}
const { data } = notification;
if (data.isNotification) {
@@ -140,13 +119,15 @@ self.addEventListener('notificationclose', async ev => {
if (!account) return;
fetch(`${origin}/api/notifications/read`, {
method: 'POST',
body: JSON.stringify({
i: account.token,
notificationIds: [data.data.id]
})
});
if (data.type === 'notification') {
fetch(`${origin}/api/notifications/read`, {
method: 'POST',
body: JSON.stringify({
i: account.token,
notificationIds: [data.body.id]
})
});
}
}
});
//#endregion
@@ -166,9 +147,7 @@ self.addEventListener('message', ev => {
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
lang = Promise.resolve(ev.data.lang);
set('lang', ev.data.lang);
fetchLocale();
swLang.setLang(ev.data.lang);
}
}
}