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

@ -68,6 +68,7 @@ import notePage from '../filters/note';
import { userPage } from '../filters/user';
import { i18n } from '@/i18n';
import * as os from '@/os';
import { markNotificationRead } from '@/scripts/mark-notification-read';
export default defineComponent({
components: {
@ -113,7 +114,17 @@ export default defineComponent({
this.readObserver.observe(this.$el);
this.connection = os.stream.useSharedConnection('main');
this.connection.on('readAllNotifications', () => this.readObserver.unobserve(this.$el));
this.connection.on('readAllNotifications', () => {
this.readObserver.unobserve(this.$el);
this.notification = markNotificationRead(this.notification);
});
this.connection.on('readNotifications', notificationIds => {
if (notificationIds.includes(this.notification.id)) {
this.readObserver.unobserve(this.$el);
this.notification = markNotificationRead(this.notification);
}
})
}
},

View File

@ -19,6 +19,7 @@
<script lang="ts">
import { defineComponent, PropType } from 'vue';
import paging from '@/scripts/paging';
import { markNotificationRead } from '@/scripts/mark-notification-read';
import XNotification from './notification.vue';
import XList from './date-separated-list.vue';
import XNote from './note.vue';
@ -85,6 +86,20 @@ export default defineComponent({
mounted() {
this.connection = os.stream.useSharedConnection('main');
this.connection.on('notification', this.onNotification);
// queue
this.connection.on('readAllNotifications', () => {
this.queue = this.queue.map(markNotificationRead);
});
this.connection.on('readNotifications', notificationIds => {
if (this.queue.length === 0) return;
for (let i = 0; i < this.queue.length; i++) {
if (notificationIds.includes(this.queue[i].id)) {
this.queue[i] = markNotificationRead(this.queue[i]);
}
}
});
},
beforeUnmount() {

View File

@ -0,0 +1,3 @@
export function markNotificationRead(notification: any) {
return { ...notification, isRead: true };
}

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);
}
}
}

View File

@ -1,4 +1,5 @@
import { publishMainStream } from '../../../services/stream';
import { pushNotification } from '../../../services/push-notification';
import { User } from '../../../models/entities/user';
import { Notification } from '../../../models/entities/notification';
import { Notifications, Users } from '../../../models';
@ -12,7 +13,7 @@ export async function readNotification(
notificationIds: Notification['id'][]
) {
// Update documents
const updatedNotificatons = await Notifications.update({
await Notifications.update({
id: In(notificationIds),
isRead: false
}, {
@ -23,10 +24,10 @@ export async function readNotification(
// ユーザーのすべての通知が既読だったら、
// 全ての(いままで未読だった)通知を(これで)読みましたよというイベントを発行
publishMainStream(userId, 'readAllNotifications');
pushNotification(userId, 'readAllNotifications', undefined);
} else {
// まだすべて既読になっていなければ、
// アップデートしたという
const updatedNotificationsIds = updatedNotificatons.generatedMaps.map(e => e.id);
publishMainStream(userId, 'readNotifications', updatedNotificationsIds);
// まだすべて既読になっていなければ、各クライアントにnotificationIdsを伝達
publishMainStream(userId, 'readNotifications', notificationIds);
pushNotification(userId, 'readNotifications', { notificationIds });
}
}

View File

@ -1,5 +1,5 @@
import { publishMainStream } from './stream';
import pushSw from './push-notification';
import { pushNotification } from './push-notification';
import { Notifications, Mutings, UserProfiles } from '../models';
import { genId } from '../misc/gen-id';
import { User } from '../models/entities/user';
@ -50,7 +50,7 @@ export async function createNotification(
publishMainStream(notifieeId, 'unreadNotification', packed);
pushSw(notifieeId, 'notification', packed);
pushNotification(notifieeId, 'notification', packed);
}
}, 2000);

View File

@ -5,7 +5,7 @@ import { MessagingMessages, UserGroupJoinings, Mutings, Users } from '../../mode
import { genId } from '../../misc/gen-id';
import { MessagingMessage } from '../../models/entities/messaging-message';
import { publishMessagingStream, publishMessagingIndexStream, publishMainStream, publishGroupMessagingStream } from '../stream';
import pushNotification from '../push-notification';
import { pushNotification } from '../push-notification';
import { Not } from 'typeorm';
import { Note } from '../../models/entities/note';
import renderNote from '../../remote/activitypub/renderer/note';

View File

@ -12,7 +12,7 @@ type pushNotificationsTypes = {
'readAllNotifications': undefined;
};
export default async function<T extends keyof pushNotificationsTypes>(userId: string, type: T, body: pushNotificationsTypes[T]) {
export async function pushNotification<T extends keyof pushNotificationsTypes>(userId: string, type: T, body: pushNotificationsTypes[T]) {
const meta = await fetchMeta();
if (!meta.enableServiceWorker || meta.swPublicKey == null || meta.swPrivateKey == null) return;