Merge pull request MisskeyIO#151 from feat-announcements-rework

feat: お知らせの確認待機時間・優先順位機能
This commit is contained in:
まっちゃとーにゅ 2023-08-19 21:12:34 +09:00 committed by GitHub
commit f2bd8ca163
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 1736 additions and 539 deletions

18
locales/index.d.ts vendored
View file

@ -1076,8 +1076,6 @@ export interface Locale {
"additionalEmojiDictionary": string; "additionalEmojiDictionary": string;
"installed": string; "installed": string;
"branding": string; "branding": string;
"newUserAnnouncementAvailable": string;
"viewAnnouncement": string;
"dialogCloseDuration": string; "dialogCloseDuration": string;
"enableServerMachineStats": string; "enableServerMachineStats": string;
"enableIdenticonGeneration": string; "enableIdenticonGeneration": string;
@ -1102,6 +1100,22 @@ export interface Locale {
"doYouAgree": string; "doYouAgree": string;
"beSureToReadThisAsItIsImportant": string; "beSureToReadThisAsItIsImportant": string;
"iHaveReadXCarefullyAndAgree": string; "iHaveReadXCarefullyAndAgree": string;
"dialog": string;
"icon": string;
"forYou": string;
"currentAnnouncements": string;
"pastAnnouncements": string;
"youHaveUnreadAnnouncements": string;
"_announcement": {
"forExistingUsers": string;
"forExistingUsersDescription": string;
"needConfirmationToRead": string;
"needConfirmationToReadDescription": string;
"end": string;
"tooManyActiveAnnouncementDescription": string;
"readConfirmTitle": string;
"readConfirmText": string;
};
"_initialAccountSetting": { "_initialAccountSetting": {
"accountCreated": string; "accountCreated": string;
"letsStartAccountSetup": string; "letsStartAccountSetup": string;

View file

@ -330,7 +330,7 @@ watch: "ウォッチ"
unwatch: "ウォッチ解除" unwatch: "ウォッチ解除"
accept: "許可" accept: "許可"
reject: "拒否" reject: "拒否"
normal: "常" normal: "常"
instanceName: "サーバー名" instanceName: "サーバー名"
instanceDescription: "サーバーの紹介" instanceDescription: "サーバーの紹介"
maintainerName: "管理者の名前" maintainerName: "管理者の名前"
@ -1073,8 +1073,6 @@ goToMisskey: "Misskeyへ"
additionalEmojiDictionary: "絵文字の追加辞書" additionalEmojiDictionary: "絵文字の追加辞書"
installed: "インストール済み" installed: "インストール済み"
branding: "ブランディング" branding: "ブランディング"
newUserAnnouncementAvailable: "新着のあなた宛てのお知らせがあります"
viewAnnouncement: "お知らせを見る"
dialogCloseDuration: "ダイアログを閉じるまでの待機時間" dialogCloseDuration: "ダイアログを閉じるまでの待機時間"
enableServerMachineStats: "サーバーのマシン情報を公開する" enableServerMachineStats: "サーバーのマシン情報を公開する"
enableIdenticonGeneration: "ユーザーごとのIdenticon生成を有効にする" enableIdenticonGeneration: "ユーザーごとのIdenticon生成を有効にする"
@ -1099,6 +1097,22 @@ expired: "期限切れ"
doYouAgree: "同意しますか?" doYouAgree: "同意しますか?"
beSureToReadThisAsItIsImportant: "重要ですので必ずお読みください。" beSureToReadThisAsItIsImportant: "重要ですので必ずお読みください。"
iHaveReadXCarefullyAndAgree: "「{x}」の内容をよく読み、同意します。" iHaveReadXCarefullyAndAgree: "「{x}」の内容をよく読み、同意します。"
dialog: "ダイアログ"
icon: "アイコン"
forYou: "あなたへ"
currentAnnouncements: "現在のお知らせ"
pastAnnouncements: "過去のお知らせ"
youHaveUnreadAnnouncements: "未読のお知らせがあります。"
_announcement:
forExistingUsers: "既存ユーザーのみ"
forExistingUsersDescription: "有効にすると、このお知らせ作成時点で存在するユーザーにのみお知らせが表示されます。無効にすると、このお知らせ作成後にアカウントを作成したユーザーにもお知らせが表示されます。"
needConfirmationToRead: "既読にするのに確認が必要"
needConfirmationToReadDescription: "有効にすると、このお知らせを既読にする際に確認ダイアログが表示されます。また、一括既読操作の対象になりません。"
end: "お知らせを終了"
tooManyActiveAnnouncementDescription: "アクティブなお知らせが多いため、UXが低下する可能性があります。終了したお知らせはアーカイブすることを検討してください。"
readConfirmTitle: "既読にしますか?"
readConfirmText: "「{title}」の内容を読み、既読にします。"
_initialAccountSetting: _initialAccountSetting:
accountCreated: "アカウントの作成が完了しました!" accountCreated: "アカウントの作成が完了しました!"

View file

@ -0,0 +1,27 @@
export class RefineAnnouncement1691649257651 {
name = 'RefineAnnouncement1691649257651'
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "announcement" ADD "display" character varying(256) NOT NULL DEFAULT 'normal'`);
await queryRunner.query(`ALTER TABLE "announcement" ADD "needConfirmationToRead" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "announcement" ADD "isActive" boolean NOT NULL DEFAULT true`);
await queryRunner.query(`ALTER TABLE "announcement" ADD "forExistingUsers" boolean NOT NULL DEFAULT false`);
// await queryRunner.query(`ALTER TABLE "announcement" ADD "userId" character varying(32)`);
await queryRunner.query(`CREATE INDEX "IDX_bc1afcc8ef7e9400cdc3c0a87e" ON "announcement" ("isActive") `);
await queryRunner.query(`CREATE INDEX "IDX_da795d3a83187e8832005ba19d" ON "announcement" ("forExistingUsers") `);
// await queryRunner.query(`CREATE INDEX "IDX_fd25dfe3da37df1715f11ba6ec" ON "announcement" ("userId") `);
// await queryRunner.query(`ALTER TABLE "announcement" ADD CONSTRAINT "FK_fd25dfe3da37df1715f11ba6ec8" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}
async down(queryRunner) {
// await queryRunner.query(`ALTER TABLE "announcement" DROP CONSTRAINT "FK_fd25dfe3da37df1715f11ba6ec8"`);
// await queryRunner.query(`DROP INDEX "public"."IDX_fd25dfe3da37df1715f11ba6ec"`);
await queryRunner.query(`DROP INDEX "public"."IDX_da795d3a83187e8832005ba19d"`);
await queryRunner.query(`DROP INDEX "public"."IDX_bc1afcc8ef7e9400cdc3c0a87e"`);
// await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "userId"`);
await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "forExistingUsers"`);
await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "isActive"`);
await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "needConfirmationToRead"`);
await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "display"`);
}
}

View file

@ -0,0 +1,11 @@
export class RefineAnnouncement21691657412740 {
name = 'RefineAnnouncement21691657412740'
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "announcement" ADD "icon" character varying(256) NOT NULL DEFAULT 'info'`);
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "announcement" DROP COLUMN "icon"`);
}
}

View file

@ -0,0 +1,354 @@
/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Inject, Injectable } from '@nestjs/common';
import { Brackets, In } from 'typeorm';
import type { AnnouncementReadsRepository, AnnouncementsRepository, UsersRepository } from '@/models/index.js';
import type { User } from '@/models/entities/User.js';
import { Announcement, AnnouncementRead } from '@/models/index.js';
import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js';
import { bindThis } from '@/decorators.js';
import { DI } from '@/di-symbols.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { IdService } from '@/core/IdService.js';
import { Packed } from '@/misc/json-schema.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
@Injectable()
export class AnnouncementService {
constructor(
@Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private idService: IdService,
private userEntityService: UserEntityService,
private announcementEntityService: AnnouncementEntityService,
private globalEventService: GlobalEventService,
) {}
@bindThis
public async create(
values: Partial<Announcement>,
): Promise<{ raw: Announcement; packed: Packed<'Announcement'> }> {
const announcement = await this.announcementsRepository
.insert({
id: this.idService.genId(),
createdAt: new Date(),
updatedAt: null,
title: values.title,
text: values.text,
imageUrl: values.imageUrl,
icon: values.icon,
display: values.display,
forExistingUsers: values.forExistingUsers,
needConfirmationToRead: values.needConfirmationToRead,
closeDuration: values.closeDuration,
displayOrder: values.displayOrder,
userId: values.userId,
})
.then((x) =>
this.announcementsRepository.findOneByOrFail(x.identifiers[0]),
);
const packed = await this.announcementEntityService.pack(
announcement,
null,
);
if (values.userId) {
this.globalEventService.publishMainStream(
values.userId,
'announcementCreated',
{
announcement: packed,
},
);
} else {
this.globalEventService.publishBroadcastStream('announcementCreated', {
announcement: packed,
});
}
return {
raw: announcement,
packed: packed,
};
}
@bindThis
public async list(
userId: User['id'] | null,
limit: number,
offset: number,
moderator: User,
): Promise<(Announcement & { userInfo: Packed<'UserLite'> | null, readCount: number })[]> {
const query = this.announcementsRepository.createQueryBuilder('announcement');
if (userId) {
query.andWhere('announcement."userId" = :userId', { userId: userId });
} else {
query.andWhere('announcement."userId" IS NULL');
}
query.orderBy({
'announcement."displayOrder"': 'DESC',
'announcement."createdAt"': 'DESC',
});
const announcements = await query
.limit(limit)
.offset(offset)
.getMany();
const reads = new Map<Announcement, number>();
for (const announcement of announcements) {
reads.set(announcement, await this.announcementReadsRepository.countBy({
announcementId: announcement.id,
}));
}
const users = await this.usersRepository.findBy({
id: In(announcements.map(a => a.userId).filter(id => id != null)),
});
const packedUsers = await this.userEntityService.packMany(users, moderator, {
detail: false,
});
return announcements.map(announcement => ({
...announcement,
userInfo: packedUsers.find(u => u.id === announcement.userId) ?? null,
readCount: reads.get(announcement) ?? 0,
}));
}
@bindThis
public async update(
announcementId: Announcement['id'],
values: Partial<Announcement>,
): Promise<{ raw: Announcement; packed: Packed<'Announcement'> }> {
const oldAnnouncement = await this.announcementsRepository.findOneByOrFail({
id: announcementId,
});
if (oldAnnouncement.userId && oldAnnouncement.userId !== values.userId) {
await this.announcementReadsRepository.delete({
announcementId: announcementId,
userId: oldAnnouncement.userId,
});
}
const announcement = await this.announcementsRepository
.update(announcementId, {
updatedAt: new Date(),
isActive: values.isActive,
title: values.title,
text: values.text,
imageUrl: values.imageUrl !== '' ? values.imageUrl : null,
icon: values.icon,
display: values.display,
forExistingUsers: values.forExistingUsers,
needConfirmationToRead: values.needConfirmationToRead,
closeDuration: values.closeDuration,
displayOrder: values.displayOrder,
userId: values.userId,
})
.then(() =>
this.announcementsRepository.findOneByOrFail({ id: announcementId }),
);
const packed = await this.announcementEntityService.pack(
announcement,
values.userId ? { id: values.userId } : null,
);
if (values.userId) {
this.globalEventService.publishMainStream(
values.userId,
'announcementCreated',
{
announcement: packed,
},
);
} else {
this.globalEventService.publishBroadcastStream('announcementCreated', {
announcement: packed,
});
}
return {
raw: announcement,
packed: packed,
};
}
@bindThis
public async delete(announcementId: Announcement['id']): Promise<void> {
await this.announcementReadsRepository.delete({
announcementId: announcementId,
});
await this.announcementsRepository.delete({ id: announcementId });
}
@bindThis
public async getAnnouncements(
me: User | null,
limit: number,
offset: number,
isActive?: boolean,
): Promise<Packed<'Announcement'>[]> {
const query = this.announcementsRepository.createQueryBuilder('announcement');
if (me) {
query.leftJoin(
AnnouncementRead,
'read',
'read."announcementId" = announcement.id AND read."userId" = :userId',
{ userId: me.id },
);
query.select([
'announcement.*',
'CASE WHEN read.id IS NULL THEN FALSE ELSE TRUE END as "isRead"',
]);
query
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."userId" = :userId', { userId: me.id });
qb.orWhere('announcement."userId" IS NULL');
}),
)
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."forExistingUsers" = false');
qb.orWhere('announcement."createdAt" > :createdAt', {
createdAt: me.createdAt,
});
}),
);
} else {
query.select([
'announcement.*',
'NULL as "isRead"',
]);
query.andWhere('announcement."userId" IS NULL');
query.andWhere('announcement."forExistingUsers" = false');
}
if (isActive !== undefined) {
query.andWhere('announcement."isActive" = :isActive', {
isActive: isActive,
});
}
query.orderBy({
'"isRead"': 'ASC',
'announcement."displayOrder"': 'DESC',
'announcement."createdAt"': 'DESC',
});
return this.announcementEntityService.packMany(
await query
.limit(limit)
.offset(offset)
.getRawMany<Announcement & { isRead?: boolean | null }>(),
me,
);
}
@bindThis
public async getUnreadAnnouncements(me: User): Promise<Packed<'Announcement'>[]> {
const query = this.announcementsRepository.createQueryBuilder('announcement');
query.leftJoinAndSelect(
AnnouncementRead,
'read',
'read."announcementId" = announcement.id AND read."userId" = :userId',
{ userId: me.id },
);
query.andWhere('read.id IS NULL');
query.andWhere('announcement."isActive" = true');
query
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."userId" = :userId', { userId: me.id });
qb.orWhere('announcement."userId" IS NULL');
}),
)
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."forExistingUsers" = false');
qb.orWhere('announcement."createdAt" > :createdAt', {
createdAt: me.createdAt,
});
}),
);
query.orderBy({
'announcement."displayOrder"': 'DESC',
'announcement."createdAt"': 'DESC',
});
return this.announcementEntityService.packMany(
await query.getMany(),
me,
);
}
@bindThis
public async countUnreadAnnouncements(me: User): Promise<number> {
const query = this.announcementsRepository.createQueryBuilder('announcement');
query.leftJoinAndSelect(
AnnouncementRead,
'read',
'read."announcementId" = announcement.id AND read."userId" = :userId',
{ userId: me.id },
);
query.andWhere('read.id IS NULL');
query.andWhere('announcement."isActive" = true');
query
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."userId" = :userId', { userId: me.id });
qb.orWhere('announcement."userId" IS NULL');
}),
)
.andWhere(
new Brackets((qb) => {
qb.orWhere('announcement."forExistingUsers" = false');
qb.orWhere('announcement."createdAt" > :createdAt', {
createdAt: me.createdAt,
});
}),
);
return query.getCount();
}
@bindThis
public async markAsRead(
me: User,
announcementId: Announcement['id'],
): Promise<void> {
try {
await this.announcementReadsRepository.insert({
id: this.idService.genId(),
createdAt: new Date(),
announcementId: announcementId,
userId: me.id,
});
} catch (e) {
return;
}
if ((await this.countUnreadAnnouncements(me)) === 0) {
this.globalEventService.publishMainStream(me.id, 'readAllAnnouncements');
}
}
}

View file

@ -7,6 +7,7 @@ import { Module } from '@nestjs/common';
import { AccountMoveService } from './AccountMoveService.js'; import { AccountMoveService } from './AccountMoveService.js';
import { AccountUpdateService } from './AccountUpdateService.js'; import { AccountUpdateService } from './AccountUpdateService.js';
import { AiService } from './AiService.js'; import { AiService } from './AiService.js';
import { AnnouncementService } from './AnnouncementService.js';
import { AntennaService } from './AntennaService.js'; import { AntennaService } from './AntennaService.js';
import { AppLockService } from './AppLockService.js'; import { AppLockService } from './AppLockService.js';
import { AchievementService } from './AchievementService.js'; import { AchievementService } from './AchievementService.js';
@ -71,6 +72,7 @@ import PerUserDriveChart from './chart/charts/per-user-drive.js';
import ApRequestChart from './chart/charts/ap-request.js'; import ApRequestChart from './chart/charts/ap-request.js';
import { ChartManagementService } from './chart/ChartManagementService.js'; import { ChartManagementService } from './chart/ChartManagementService.js';
import { AbuseUserReportEntityService } from './entities/AbuseUserReportEntityService.js'; import { AbuseUserReportEntityService } from './entities/AbuseUserReportEntityService.js';
import { AnnouncementEntityService } from './entities/AnnouncementEntityService.js';
import { AntennaEntityService } from './entities/AntennaEntityService.js'; import { AntennaEntityService } from './entities/AntennaEntityService.js';
import { AppEntityService } from './entities/AppEntityService.js'; import { AppEntityService } from './entities/AppEntityService.js';
import { AuthSessionEntityService } from './entities/AuthSessionEntityService.js'; import { AuthSessionEntityService } from './entities/AuthSessionEntityService.js';
@ -130,6 +132,7 @@ const $LoggerService: Provider = { provide: 'LoggerService', useExisting: Logger
const $AccountMoveService: Provider = { provide: 'AccountMoveService', useExisting: AccountMoveService }; const $AccountMoveService: Provider = { provide: 'AccountMoveService', useExisting: AccountMoveService };
const $AccountUpdateService: Provider = { provide: 'AccountUpdateService', useExisting: AccountUpdateService }; const $AccountUpdateService: Provider = { provide: 'AccountUpdateService', useExisting: AccountUpdateService };
const $AiService: Provider = { provide: 'AiService', useExisting: AiService }; const $AiService: Provider = { provide: 'AiService', useExisting: AiService };
const $AnnouncementService: Provider = { provide: 'AnnouncementService', useExisting: AnnouncementService };
const $AntennaService: Provider = { provide: 'AntennaService', useExisting: AntennaService }; const $AntennaService: Provider = { provide: 'AntennaService', useExisting: AntennaService };
const $AppLockService: Provider = { provide: 'AppLockService', useExisting: AppLockService }; const $AppLockService: Provider = { provide: 'AppLockService', useExisting: AppLockService };
const $AchievementService: Provider = { provide: 'AchievementService', useExisting: AchievementService }; const $AchievementService: Provider = { provide: 'AchievementService', useExisting: AchievementService };
@ -196,6 +199,7 @@ const $ApRequestChart: Provider = { provide: 'ApRequestChart', useExisting: ApRe
const $ChartManagementService: Provider = { provide: 'ChartManagementService', useExisting: ChartManagementService }; const $ChartManagementService: Provider = { provide: 'ChartManagementService', useExisting: ChartManagementService };
const $AbuseUserReportEntityService: Provider = { provide: 'AbuseUserReportEntityService', useExisting: AbuseUserReportEntityService }; const $AbuseUserReportEntityService: Provider = { provide: 'AbuseUserReportEntityService', useExisting: AbuseUserReportEntityService };
const $AnnouncementEntityService: Provider = { provide: 'AnnouncementEntityService', useExisting: AnnouncementEntityService };
const $AntennaEntityService: Provider = { provide: 'AntennaEntityService', useExisting: AntennaEntityService }; const $AntennaEntityService: Provider = { provide: 'AntennaEntityService', useExisting: AntennaEntityService };
const $AppEntityService: Provider = { provide: 'AppEntityService', useExisting: AppEntityService }; const $AppEntityService: Provider = { provide: 'AppEntityService', useExisting: AppEntityService };
const $AuthSessionEntityService: Provider = { provide: 'AuthSessionEntityService', useExisting: AuthSessionEntityService }; const $AuthSessionEntityService: Provider = { provide: 'AuthSessionEntityService', useExisting: AuthSessionEntityService };
@ -257,6 +261,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
AccountMoveService, AccountMoveService,
AccountUpdateService, AccountUpdateService,
AiService, AiService,
AnnouncementService,
AntennaService, AntennaService,
AppLockService, AppLockService,
AchievementService, AchievementService,
@ -321,6 +326,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
ApRequestChart, ApRequestChart,
ChartManagementService, ChartManagementService,
AbuseUserReportEntityService, AbuseUserReportEntityService,
AnnouncementEntityService,
AntennaEntityService, AntennaEntityService,
AppEntityService, AppEntityService,
AuthSessionEntityService, AuthSessionEntityService,
@ -377,6 +383,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$AccountMoveService, $AccountMoveService,
$AccountUpdateService, $AccountUpdateService,
$AiService, $AiService,
$AnnouncementService,
$AntennaService, $AntennaService,
$AppLockService, $AppLockService,
$AchievementService, $AchievementService,
@ -441,6 +448,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$ApRequestChart, $ApRequestChart,
$ChartManagementService, $ChartManagementService,
$AbuseUserReportEntityService, $AbuseUserReportEntityService,
$AnnouncementEntityService,
$AntennaEntityService, $AntennaEntityService,
$AppEntityService, $AppEntityService,
$AuthSessionEntityService, $AuthSessionEntityService,
@ -498,6 +506,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
AccountMoveService, AccountMoveService,
AccountUpdateService, AccountUpdateService,
AiService, AiService,
AnnouncementService,
AntennaService, AntennaService,
AppLockService, AppLockService,
AchievementService, AchievementService,
@ -561,6 +570,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
ApRequestChart, ApRequestChart,
ChartManagementService, ChartManagementService,
AbuseUserReportEntityService, AbuseUserReportEntityService,
AnnouncementEntityService,
AntennaEntityService, AntennaEntityService,
AppEntityService, AppEntityService,
AuthSessionEntityService, AuthSessionEntityService,
@ -617,6 +627,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$AccountMoveService, $AccountMoveService,
$AccountUpdateService, $AccountUpdateService,
$AiService, $AiService,
$AnnouncementService,
$AntennaService, $AntennaService,
$AppLockService, $AppLockService,
$AchievementService, $AchievementService,
@ -680,6 +691,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$ApRequestChart, $ApRequestChart,
$ChartManagementService, $ChartManagementService,
$AbuseUserReportEntityService, $AbuseUserReportEntityService,
$AnnouncementEntityService,
$AntennaEntityService, $AntennaEntityService,
$AppEntityService, $AppEntityService,
$AuthSessionEntityService, $AuthSessionEntityService,

View file

@ -0,0 +1,71 @@
/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
import type {
AnnouncementReadsRepository,
AnnouncementsRepository,
} from '@/models/index.js';
import type { Packed } from '@/misc/json-schema.js';
import { bindThis } from '@/decorators.js';
import { Announcement, User } from '@/models/index.js';
@Injectable()
export class AnnouncementEntityService {
constructor(
@Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
) {
}
@bindThis
public async pack(
src: Announcement['id'] | Announcement & { isRead?: boolean | null },
me: { id: User['id'] } | null | undefined,
): Promise<Packed<'Announcement'>> {
const announcement = typeof src === 'object'
? src
: await this.announcementsRepository.findOneByOrFail({
id: src,
}) as Announcement & { isRead?: boolean | null };
if (me && announcement.isRead === undefined) {
announcement.isRead = await this.announcementReadsRepository.countBy({
announcementId: announcement.id,
userId: me.id,
}).then(count => count > 0);
}
return {
id: announcement.id,
createdAt: announcement.createdAt.toISOString(),
updatedAt: announcement.updatedAt?.toISOString() ?? null,
title: announcement.title,
text: announcement.text,
imageUrl: announcement.imageUrl,
icon: announcement.icon,
display: announcement.display,
forYou: announcement.userId === me?.id,
needConfirmationToRead: announcement.needConfirmationToRead,
closeDuration: announcement.closeDuration,
displayOrder: announcement.displayOrder,
isRead: announcement.isRead !== null ? announcement.isRead : undefined,
};
}
@bindThis
public async packMany(
announcements: (Announcement['id'] | Announcement & { isRead?: boolean | null } | Announcement)[],
me: { id: User['id'] } | null | undefined,
) : Promise<Packed<'Announcement'>[]> {
return (await Promise.allSettled(announcements.map(x => this.pack(x, me))))
.filter(result => result.status === 'fulfilled')
.map(result => (result as PromiseFulfilledResult<Packed<'Announcement'>>).value);
}
}

View file

@ -4,7 +4,6 @@
*/ */
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { In, IsNull, Not } from 'typeorm';
import * as Redis from 'ioredis'; import * as Redis from 'ioredis';
import _Ajv from 'ajv'; import _Ajv from 'ajv';
import { ModuleRef } from '@nestjs/core'; import { ModuleRef } from '@nestjs/core';
@ -49,7 +48,7 @@ import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js';
import { FederatedInstanceService } from '@/core/FederatedInstanceService.js'; import { FederatedInstanceService } from '@/core/FederatedInstanceService.js';
import { IdentifiableError } from '@/misc/identifiable-error.js'; import { IdentifiableError } from '@/misc/identifiable-error.js';
import type { OnModuleInit } from '@nestjs/common'; import type { OnModuleInit } from '@nestjs/common';
import type { AntennaService } from '../AntennaService.js'; import type { AnnouncementService } from '../AnnouncementService.js';
import type { CustomEmojiService } from '../CustomEmojiService.js'; import type { CustomEmojiService } from '../CustomEmojiService.js';
import type { NoteEntityService } from './NoteEntityService.js'; import type { NoteEntityService } from './NoteEntityService.js';
import type { DriveFileEntityService } from './DriveFileEntityService.js'; import type { DriveFileEntityService } from './DriveFileEntityService.js';
@ -85,7 +84,7 @@ export class UserEntityService implements OnModuleInit {
private driveFileEntityService: DriveFileEntityService; private driveFileEntityService: DriveFileEntityService;
private pageEntityService: PageEntityService; private pageEntityService: PageEntityService;
private customEmojiService: CustomEmojiService; private customEmojiService: CustomEmojiService;
private antennaService: AntennaService; private announcementService: AnnouncementService;
private roleService: RoleService; private roleService: RoleService;
private federatedInstanceService: FederatedInstanceService; private federatedInstanceService: FederatedInstanceService;
@ -164,7 +163,7 @@ export class UserEntityService implements OnModuleInit {
this.driveFileEntityService = this.moduleRef.get('DriveFileEntityService'); this.driveFileEntityService = this.moduleRef.get('DriveFileEntityService');
this.pageEntityService = this.moduleRef.get('PageEntityService'); this.pageEntityService = this.moduleRef.get('PageEntityService');
this.customEmojiService = this.moduleRef.get('CustomEmojiService'); this.customEmojiService = this.moduleRef.get('CustomEmojiService');
this.antennaService = this.moduleRef.get('AntennaService'); this.announcementService = this.moduleRef.get('AnnouncementService');
this.roleService = this.moduleRef.get('RoleService'); this.roleService = this.moduleRef.get('RoleService');
this.federatedInstanceService = this.moduleRef.get('FederatedInstanceService'); this.federatedInstanceService = this.moduleRef.get('FederatedInstanceService');
} }
@ -244,21 +243,6 @@ export class UserEntityService implements OnModuleInit {
}); });
} }
@bindThis
public async getHasUnreadAnnouncement(userId: User['id']): Promise<boolean> {
const reads = await this.announcementReadsRepository.findBy({
userId: userId,
});
const id = reads.length > 0 ? Not(In(reads.map(read => read.announcementId))) : undefined;
const count = await this.announcementsRepository.countBy([
{ id, userId: IsNull() },
{ id, userId: userId },
]);
return count > 0;
}
@bindThis @bindThis
public async getHasUnreadAntenna(userId: User['id']): Promise<boolean> { public async getHasUnreadAntenna(userId: User['id']): Promise<boolean> {
/* /*
@ -387,6 +371,7 @@ export class UserEntityService implements OnModuleInit {
const isModerator = isMe && opts.detail ? await this.roleService.isModerator(user) : null; const isModerator = isMe && opts.detail ? await this.roleService.isModerator(user) : null;
const isAdmin = isMe && opts.detail ? await this.roleService.isAdministrator(user) : null; const isAdmin = isMe && opts.detail ? await this.roleService.isAdministrator(user) : null;
const policies = opts.detail ? await this.roleService.getUserPolicies(user.id) : null; const policies = opts.detail ? await this.roleService.getUserPolicies(user.id) : null;
const unreadAnnouncements = isMe && opts.detail ? await this.announcementService.getUnreadAnnouncements(user) : null;
const falsy = opts.detail ? false : undefined; const falsy = opts.detail ? false : undefined;
@ -498,7 +483,8 @@ export class UserEntityService implements OnModuleInit {
where: { userId: user.id, isMentioned: true }, where: { userId: user.id, isMentioned: true },
take: 1, take: 1,
}).then(count => count > 0), }).then(count => count > 0),
hasUnreadAnnouncement: this.getHasUnreadAnnouncement(user.id), hasUnreadAnnouncement: unreadAnnouncements!.length > 0,
unreadAnnouncements,
hasUnreadAntenna: this.getHasUnreadAntenna(user.id), hasUnreadAntenna: this.getHasUnreadAntenna(user.id),
hasUnreadChannel: false, // 後方互換性のため hasUnreadChannel: false, // 後方互換性のため
hasUnreadNotification: this.getHasUnreadNotification(user.id), hasUnreadNotification: this.getHasUnreadNotification(user.id),

View file

@ -38,6 +38,7 @@ import { packedQueueCountSchema } from '@/models/json-schema/queue.js';
import { packedRenoteMutingSchema } from '@/models/json-schema/renote-muting.js'; import { packedRenoteMutingSchema } from '@/models/json-schema/renote-muting.js';
import { packedRoleSchema } from '@/models/json-schema/role.js'; import { packedRoleSchema } from '@/models/json-schema/role.js';
import { packedUserListSchema } from '@/models/json-schema/user-list.js'; import { packedUserListSchema } from '@/models/json-schema/user-list.js';
import { packedAnnouncementSchema } from '@/models/json-schema/announcement.js';
export const refs = { export const refs = {
UserLite: packedUserLiteSchema, UserLite: packedUserLiteSchema,
@ -49,6 +50,7 @@ export const refs = {
User: packedUserSchema, User: packedUserSchema,
UserList: packedUserListSchema, UserList: packedUserListSchema,
Announcement: packedAnnouncementSchema,
App: packedAppSchema, App: packedAppSchema,
Note: packedNoteSchema, Note: packedNoteSchema,
NoteReaction: packedNoteReactionSchema, NoteReaction: packedNoteReactionSchema,

View file

@ -3,8 +3,9 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { Entity, Index, Column, PrimaryColumn } from 'typeorm'; import { Entity, Index, Column, PrimaryColumn, ManyToOne, JoinColumn } from 'typeorm';
import { id } from '../id.js'; import { id } from '../id.js';
import { User } from './User.js';
@Entity() @Entity()
export class Announcement { export class Announcement {
@ -38,19 +39,26 @@ export class Announcement {
}) })
public imageUrl: string | null; public imageUrl: string | null;
// UIに表示する際の並び順用(大きいほど先頭) // info, warning, error, success
@Index()
@Column('integer', {
default: 0,
})
public displayOrder: number;
@Index()
@Column('varchar', { @Column('varchar', {
...id(), length: 256, nullable: false,
nullable: true, default: 'info',
}) })
public userId: string | null; public icon: string;
// normal ... お知らせページ掲載
// banner ... お知らせページ掲載 + バナー表示
// dialog ... お知らせページ掲載 + ダイアログ表示
@Column('varchar', {
length: 256, nullable: false,
default: 'normal',
})
public display: string;
@Column('boolean', {
default: false,
})
public needConfirmationToRead: boolean;
@Column('integer', { @Column('integer', {
nullable: false, nullable: false,
@ -58,6 +66,39 @@ export class Announcement {
}) })
public closeDuration: number; public closeDuration: number;
@Index()
@Column('boolean', {
default: true,
})
public isActive: boolean;
// UIに表示する際の並び順用(大きいほど先頭)
@Index()
@Column('integer', {
nullable: false,
default: 0,
})
public displayOrder: number;
@Index()
@Column('boolean', {
default: false,
})
public forExistingUsers: boolean;
@Index()
@Column({
...id(),
nullable: true,
})
public userId: User['id'] | null;
@ManyToOne(type => User, {
onDelete: 'CASCADE',
})
@JoinColumn()
public user: User | null;
constructor(data: Partial<Announcement>) { constructor(data: Partial<Announcement>) {
if (data == null) return; if (data == null) return;

View file

@ -0,0 +1,66 @@
/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
export const packedAnnouncementSchema = {
type: 'object',
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'id',
example: 'xxxxxxxxxx',
},
createdAt: {
type: 'string',
optional: false, nullable: false,
format: 'date-time',
},
updatedAt: {
type: 'string',
optional: false, nullable: true,
format: 'date-time',
},
text: {
type: 'string',
optional: false, nullable: false,
},
title: {
type: 'string',
optional: false, nullable: false,
},
imageUrl: {
type: 'string',
optional: false, nullable: true,
},
icon: {
type: 'string',
optional: false, nullable: false,
},
display: {
type: 'string',
optional: false, nullable: false,
},
forYou: {
type: 'boolean',
optional: false, nullable: false,
},
needConfirmationToRead: {
type: 'boolean',
optional: false, nullable: false,
},
closeDuration: {
type: 'number',
optional: false, nullable: false,
},
displayOrder: {
type: 'number',
optional: false, nullable: false,
},
isRead: {
type: 'boolean',
optional: true, nullable: false,
},
},
} as const;

View file

@ -3,11 +3,9 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { Inject, Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import type { AnnouncementsRepository } from '@/models/index.js'; import { AnnouncementService } from '@/core/AnnouncementService.js';
import { IdService } from '@/core/IdService.js';
import { DI } from '@/di-symbols.js';
export const meta = { export const meta = {
tags: ['admin'], tags: ['admin'],
@ -47,6 +45,26 @@ export const meta = {
type: 'string', type: 'string',
optional: false, nullable: true, optional: false, nullable: true,
}, },
icon: {
type: 'string',
optional: false, nullable: false,
},
display: {
type: 'string',
optional: false, nullable: false,
},
forExistingUsers: {
type: 'boolean',
optional: false, nullable: false,
},
needConfirmationToRead: {
type: 'boolean',
optional: false, nullable: false,
},
closeDuration: {
type: 'number',
optional: false, nullable: false,
},
displayOrder: { displayOrder: {
type: 'number', type: 'number',
optional: false, nullable: false, optional: false, nullable: false,
@ -55,10 +73,6 @@ export const meta = {
type: 'string', type: 'string',
optional: false, nullable: true, optional: false, nullable: true,
}, },
closeDuration: {
type: 'number',
optional: false, nullable: false,
},
}, },
}, },
} as const; } as const;
@ -69,9 +83,13 @@ export const paramDef = {
title: { type: 'string', minLength: 1 }, title: { type: 'string', minLength: 1 },
text: { type: 'string', minLength: 1 }, text: { type: 'string', minLength: 1 },
imageUrl: { type: 'string', nullable: true, minLength: 1 }, imageUrl: { type: 'string', nullable: true, minLength: 1 },
displayOrder: { type: 'number' }, icon: { type: 'string', enum: ['info', 'warning', 'error', 'success'], default: 'info' },
userId: { type: 'string', nullable: true, format: 'misskey:id' }, display: { type: 'string', enum: ['normal', 'banner', 'dialog'], default: 'normal' },
closeDuration: { type: 'number', nullable: false }, forExistingUsers: { type: 'boolean', default: false },
needConfirmationToRead: { type: 'boolean', default: false },
closeDuration: { type: 'number', default: 0 },
displayOrder: { type: 'number', default: 0 },
userId: { type: 'string', format: 'misskey:id', nullable: true, default: null },
}, },
required: ['title', 'text', 'imageUrl'], required: ['title', 'text', 'imageUrl'],
} as const; } as const;
@ -80,25 +98,39 @@ export const paramDef = {
@Injectable() @Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor( constructor(
@Inject(DI.announcementsRepository) private announcementService: AnnouncementService,
private announcementsRepository: AnnouncementsRepository,
private idService: IdService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const announcement = await this.announcementsRepository.insert({ const { raw, packed } = await this.announcementService.create({
id: this.idService.genId(),
createdAt: new Date(), createdAt: new Date(),
updatedAt: null, updatedAt: null,
title: ps.title, title: ps.title,
text: ps.text, text: ps.text,
imageUrl: ps.imageUrl, imageUrl: ps.imageUrl,
displayOrder: ps.displayOrder, icon: ps.icon,
userId: ps.userId ?? null, display: ps.display,
forExistingUsers: ps.forExistingUsers,
needConfirmationToRead: ps.needConfirmationToRead,
closeDuration: ps.closeDuration, closeDuration: ps.closeDuration,
}).then(x => this.announcementsRepository.findOneByOrFail(x.identifiers[0])); displayOrder: ps.displayOrder,
userId: ps.userId,
});
return Object.assign({}, announcement, { createdAt: announcement.createdAt.toISOString(), updatedAt: null }); return {
id: packed.id,
createdAt: packed.createdAt,
updatedAt: packed.updatedAt,
title: packed.title,
text: packed.text,
imageUrl: packed.imageUrl,
icon: packed.icon,
display: packed.display,
forExistingUsers: raw.forExistingUsers,
needConfirmationToRead: packed.needConfirmationToRead,
closeDuration: packed.closeDuration,
displayOrder: packed.displayOrder,
userId: raw.userId,
};
}); });
} }
} }

View file

@ -5,9 +5,10 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import type { AnnouncementsRepository } from '@/models/index.js'; import { ApiError } from '@/server/api/error.js';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import { ApiError } from '../../../error.js'; import type { AnnouncementsRepository } from '@/models/index.js';
import { AnnouncementService } from '@/core/AnnouncementService.js';
export const meta = { export const meta = {
tags: ['admin'], tags: ['admin'],
@ -38,13 +39,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor( constructor(
@Inject(DI.announcementsRepository) @Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository, private announcementsRepository: AnnouncementsRepository,
private announcementService: AnnouncementService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const announcement = await this.announcementsRepository.findOneBy({ id: ps.id }); const announcement = await this.announcementsRepository.findOneBy({ id: ps.id });
if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement); if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement);
await this.announcementsRepository.delete(announcement.id); await this.announcementService.delete(announcement.id);
}); });
} }
} }

View file

@ -3,14 +3,9 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { Inject, Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { In } from 'typeorm';
import type { AnnouncementsRepository, AnnouncementReadsRepository, UsersRepository } from '@/models/index.js';
import type { Announcement } from '@/models/entities/Announcement.js';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import { QueryService } from '@/core/QueryService.js'; import { AnnouncementService } from '@/core/AnnouncementService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { DI } from '@/di-symbols.js';
export const meta = { export const meta = {
tags: ['admin'], tags: ['admin'],
@ -41,18 +36,42 @@ export const meta = {
optional: false, nullable: true, optional: false, nullable: true,
format: 'date-time', format: 'date-time',
}, },
text: { isActive: {
type: 'string', type: 'boolean',
optional: false, nullable: false, optional: false, nullable: false,
}, },
title: { title: {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: false,
}, },
text: {
type: 'string',
optional: false, nullable: false,
},
imageUrl: { imageUrl: {
type: 'string', type: 'string',
optional: false, nullable: true, optional: false, nullable: true,
}, },
icon: {
type: 'string',
optional: false, nullable: false,
},
display: {
type: 'string',
optional: false, nullable: false,
},
forExistingUsers: {
type: 'boolean',
optional: false, nullable: false,
},
needConfirmationToRead: {
type: 'boolean',
optional: false, nullable: false,
},
closeDuration: {
type: 'number',
optional: false, nullable: false,
},
displayOrder: { displayOrder: {
type: 'number', type: 'number',
optional: false, nullable: false, optional: false, nullable: false,
@ -63,14 +82,10 @@ export const meta = {
}, },
user: { user: {
type: 'object', type: 'object',
optional: true, nullable: false, optional: false, nullable: true,
ref: 'UserLite', ref: 'UserLite',
}, },
reads: { readCount: {
type: 'number',
optional: false, nullable: false,
},
closeDuration: {
type: 'number', type: 'number',
optional: false, nullable: false, optional: false, nullable: false,
}, },
@ -84,7 +99,7 @@ export const paramDef = {
properties: { properties: {
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
offset: { type: 'integer', default: 0 }, offset: { type: 'integer', default: 0 },
userId: { type: 'string', format: 'misskey:id' }, userId: { type: 'string', format: 'misskey:id', nullable: true },
}, },
required: [], required: [],
} as const; } as const;
@ -93,62 +108,28 @@ export const paramDef = {
@Injectable() @Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor( constructor(
@Inject(DI.announcementsRepository) private announcementService: AnnouncementService,
private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private userEntityService: UserEntityService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const query = this.announcementsRepository.createQueryBuilder('announcement'); const announcements = await this.announcementService.list(ps.userId ?? null, ps.limit, ps.offset, me);
if (ps.userId) {
query.where('"userId" = :userId', { userId: ps.userId });
} else {
query.where('"userId" IS NULL');
}
query.orderBy({
'announcement."displayOrder"': 'DESC',
'announcement."createdAt"': 'DESC',
});
const announcements = await query
.offset(ps.offset)
.limit(ps.limit)
.getMany();
const reads = new Map<Announcement, number>();
for (const announcement of announcements) {
reads.set(announcement, await this.announcementReadsRepository.countBy({
announcementId: announcement.id,
}));
}
const users = await this.usersRepository.findBy({
id: In(announcements.map(a => a.userId).filter(id => id != null)),
});
const packedUsers = await this.userEntityService.packMany(users, me, {
detail: false,
});
return announcements.map(announcement => ({ return announcements.map(announcement => ({
id: announcement.id, id: announcement.id,
createdAt: announcement.createdAt.toISOString(), createdAt: announcement.createdAt.toISOString(),
updatedAt: announcement.updatedAt?.toISOString() ?? null, updatedAt: announcement.updatedAt?.toISOString() ?? null,
isActive: announcement.isActive,
title: announcement.title, title: announcement.title,
text: announcement.text, text: announcement.text,
imageUrl: announcement.imageUrl, imageUrl: announcement.imageUrl,
icon: announcement.icon,
display: announcement.display,
forExistingUsers: announcement.forExistingUsers,
needConfirmationToRead: announcement.needConfirmationToRead,
closeDuration: announcement.closeDuration,
displayOrder: announcement.displayOrder, displayOrder: announcement.displayOrder,
userId: announcement.userId, userId: announcement.userId,
user: packedUsers.find(user => user.id === announcement.userId), user: announcement.userInfo,
reads: reads.get(announcement)!, readCount: announcement.readCount,
closeDuration: announcement.closeDuration,
})); }));
}); });
} }

View file

@ -5,9 +5,10 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import type { AnnouncementReadsRepository, AnnouncementsRepository } from '@/models/index.js'; import { ApiError } from '@/server/api/error.js';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import { ApiError } from '../../../error.js'; import type { AnnouncementsRepository } from '@/models/index.js';
import { AnnouncementService } from '@/core/AnnouncementService.js';
export const meta = { export const meta = {
tags: ['admin'], tags: ['admin'],
@ -31,11 +32,15 @@ export const paramDef = {
title: { type: 'string', minLength: 1 }, title: { type: 'string', minLength: 1 },
text: { type: 'string', minLength: 1 }, text: { type: 'string', minLength: 1 },
imageUrl: { type: 'string', nullable: true, minLength: 0 }, imageUrl: { type: 'string', nullable: true, minLength: 0 },
displayOrder: { type: 'number' }, icon: { type: 'string', enum: ['info', 'warning', 'error', 'success'] },
userId: { type: 'string', nullable: true, format: 'misskey:id' }, display: { type: 'string', enum: ['normal', 'banner', 'dialog'] },
closeDuration: { type: 'number', nullable: false }, forExistingUsers: { type: 'boolean' },
needConfirmationToRead: { type: 'boolean' },
closeDuration: { type: 'number', default: 0 },
displayOrder: { type: 'number', default: 0 },
isActive: { type: 'boolean' },
}, },
required: ['id', 'title', 'text', 'imageUrl', 'closeDuration'], required: ['id'],
} as const; } as const;
// eslint-disable-next-line import/no-default-export // eslint-disable-next-line import/no-default-export
@ -45,28 +50,14 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
@Inject(DI.announcementsRepository) @Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository, private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository) private announcementService: AnnouncementService,
private announcementsReadsRepository: AnnouncementReadsRepository,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const announcement = await this.announcementsRepository.findOneBy({ id: ps.id }); const announcement = await this.announcementsRepository.findOneBy({ id: ps.id });
if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement); if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement);
if (announcement.userId && announcement.userId !== ps.userId) { await this.announcementService.update(announcement.id, ps);
await this.announcementsReadsRepository.delete({ id: announcement.id, userId: announcement.userId });
}
await this.announcementsRepository.update(announcement.id, {
updatedAt: new Date(),
title: ps.title,
text: ps.text,
/* eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- 空の文字列の場合、nullを渡すようにするため */
imageUrl: ps.imageUrl || null,
displayOrder: ps.displayOrder,
userId: ps.userId ?? null,
closeDuration: ps.closeDuration,
});
}); });
} }
} }

View file

@ -4,10 +4,12 @@
*/ */
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { Brackets } from 'typeorm';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import { QueryService } from '@/core/QueryService.js';
import { AnnouncementService } from '@/core/AnnouncementService.js';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import type { AnnouncementsRepository } from '@/models/index.js'; import type { AnnouncementReadsRepository, AnnouncementsRepository } from '@/models/index.js';
import { Announcement, AnnouncementRead } from '@/models/index.js';
export const meta = { export const meta = {
tags: ['meta'], tags: ['meta'],
@ -20,48 +22,7 @@ export const meta = {
items: { items: {
type: 'object', type: 'object',
optional: false, nullable: false, optional: false, nullable: false,
properties: { ref: 'Announcement',
id: {
type: 'string',
optional: false, nullable: false,
format: 'id',
example: 'xxxxxxxxxx',
},
createdAt: {
type: 'string',
optional: false, nullable: false,
format: 'date-time',
},
updatedAt: {
type: 'string',
optional: false, nullable: true,
format: 'date-time',
},
text: {
type: 'string',
optional: false, nullable: false,
},
title: {
type: 'string',
optional: false, nullable: false,
},
imageUrl: {
type: 'string',
optional: false, nullable: true,
},
isRead: {
type: 'boolean',
optional: true, nullable: false,
},
isPrivate: {
type: 'boolean',
optional: false, nullable: true,
},
closeDuration: {
type: 'number',
optional: false, nullable: false,
},
},
}, },
}, },
} as const; } as const;
@ -71,8 +32,7 @@ export const paramDef = {
properties: { properties: {
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
offset: { type: 'integer', default: 0 }, offset: { type: 'integer', default: 0 },
withUnreads: { type: 'boolean', default: false }, isActive: { type: 'boolean', default: true },
privateOnly: { type: 'boolean', default: false },
}, },
required: [], required: [],
} as const; } as const;
@ -83,46 +43,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor( constructor(
@Inject(DI.announcementsRepository) @Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository, private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
private queryService: QueryService,
private announcementService: AnnouncementService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const query = this.announcementsRepository.createQueryBuilder('announcement'); return this.announcementService.getAnnouncements(me, ps.limit, ps.offset, ps.isActive);
if (me) {
query.leftJoinAndSelect(AnnouncementRead, 'reads', 'reads."announcementId" = announcement.id AND reads."userId" = :userId', { userId: me.id });
query.select([
'announcement.*',
'CASE WHEN reads.id IS NULL THEN FALSE ELSE TRUE END as "isRead"',
]);
if (ps.privateOnly) {
query.where('announcement."userId" = :userId', { userId: me.id });
} else {
query.where('announcement."userId" IS NULL');
query.orWhere('announcement."userId" = :userId', { userId: me.id });
}
} else {
query.select([
'announcement.*',
'FALSE as "isRead"',
]);
query.where('announcement."userId" IS NULL');
}
query.orderBy({
'"isRead"': 'ASC',
'announcement."displayOrder"': 'DESC',
'announcement."createdAt"': 'DESC',
});
const announcements = await query
.offset(ps.offset)
.limit(ps.limit)
.getRawMany<Announcement & { isRead: boolean }>();
return (ps.withUnreads ? announcements.filter(i => !i.isRead) : announcements).map((a) => ({
...a,
createdAt: a.createdAt.toISOString(),
updatedAt: a.updatedAt?.toISOString() ?? null,
isPrivate: !!a.userId,
}));
}); });
} }
} }

View file

@ -3,15 +3,9 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { Inject, Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { IsNull } from 'typeorm';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import { IdService } from '@/core/IdService.js'; import { AnnouncementService } from '@/core/AnnouncementService.js';
import type { AnnouncementReadsRepository, AnnouncementsRepository } from '@/models/index.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { DI } from '@/di-symbols.js';
import { ApiError } from '../../error.js';
export const meta = { export const meta = {
tags: ['account'], tags: ['account'],
@ -21,11 +15,6 @@ export const meta = {
kind: 'write:account', kind: 'write:account',
errors: { errors: {
noSuchAnnouncement: {
message: 'No such announcement.',
code: 'NO_SUCH_ANNOUNCEMENT',
id: '184663db-df88-4bc2-8b52-fb85f0681939',
},
}, },
} as const; } as const;
@ -41,58 +30,10 @@ export const paramDef = {
@Injectable() @Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor( constructor(
@Inject(DI.announcementsRepository) private announcementService: AnnouncementService,
private announcementsRepository: AnnouncementsRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
private userEntityService: UserEntityService,
private idService: IdService,
private globalEventService: GlobalEventService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
// Check if announcement exists await this.announcementService.markAsRead(me, ps.announcementId);
const announcementExist = await this.announcementsRepository.exist({
where: [
{
id: ps.announcementId,
userId: IsNull(),
},
{
id: ps.announcementId,
userId: me.id,
}
]
});
if (!announcementExist) {
throw new ApiError(meta.errors.noSuchAnnouncement);
}
// Check if already read
const alreadyRead = await this.announcementReadsRepository.exist({
where: {
announcementId: ps.announcementId,
userId: me.id,
},
});
if (alreadyRead) {
return;
}
// Create read
await this.announcementReadsRepository.insert({
id: this.idService.genId(),
createdAt: new Date(),
announcementId: ps.announcementId,
userId: me.id,
});
if (!await this.userEntityService.getHasUnreadAnnouncement(me.id)) {
this.globalEventService.publishMainStream(me.id, 'readAllAnnouncements');
}
}); });
} }
} }

View file

@ -64,6 +64,9 @@ export interface BroadcastTypes {
[other: string]: any; [other: string]: any;
}[]; }[];
}; };
announcementCreated: {
announcement: Packed<'Announcement'>;
};
} }
export interface MainStreamTypes { export interface MainStreamTypes {
@ -105,6 +108,9 @@ export interface MainStreamTypes {
driveFileCreated: Packed<'DriveFile'>; driveFileCreated: Packed<'DriveFile'>;
readAntenna: Antenna; readAntenna: Antenna;
receiveFollowRequest: Packed<'User'>; receiveFollowRequest: Packed<'User'>;
announcementCreated: {
announcement: Packed<'Announcement'>;
};
} }
export interface DriveStreamTypes { export interface DriveStreamTypes {

View file

@ -162,6 +162,7 @@ describe('ユーザー', () => {
hasUnreadChannel: user.hasUnreadChannel, hasUnreadChannel: user.hasUnreadChannel,
hasUnreadNotification: user.hasUnreadNotification, hasUnreadNotification: user.hasUnreadNotification,
hasPendingReceivedFollowRequest: user.hasPendingReceivedFollowRequest, hasPendingReceivedFollowRequest: user.hasPendingReceivedFollowRequest,
unreadAnnouncements: user.unreadAnnouncements,
mutedWords: user.mutedWords, mutedWords: user.mutedWords,
mutedInstances: user.mutedInstances, mutedInstances: user.mutedInstances,
mutingNotificationTypes: user.mutingNotificationTypes, mutingNotificationTypes: user.mutingNotificationTypes,
@ -409,6 +410,7 @@ describe('ユーザー', () => {
assert.strictEqual(response.hasUnreadChannel, false); assert.strictEqual(response.hasUnreadChannel, false);
assert.strictEqual(response.hasUnreadNotification, false); assert.strictEqual(response.hasUnreadNotification, false);
assert.strictEqual(response.hasPendingReceivedFollowRequest, false); assert.strictEqual(response.hasPendingReceivedFollowRequest, false);
assert.deepStrictEqual(response.unreadAnnouncements, []);
assert.deepStrictEqual(response.mutedWords, []); assert.deepStrictEqual(response.mutedWords, []);
assert.deepStrictEqual(response.mutedInstances, []); assert.deepStrictEqual(response.mutedInstances, []);
assert.deepStrictEqual(response.mutingNotificationTypes, []); assert.deepStrictEqual(response.mutingNotificationTypes, []);

View file

@ -0,0 +1,196 @@
/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
process.env.NODE_ENV = 'test';
import { ModuleMocker } from 'jest-mock';
import { Test } from '@nestjs/testing';
import { jest } from '@jest/globals';
import type { Announcement, AnnouncementsRepository, AnnouncementReadsRepository, UsersRepository, User } from '@/models/index.js';
import { secureRndstr } from '@/misc/secure-rndstr.js';
import { GlobalModule } from '@/GlobalModule.js';
import { IdService } from '@/core/IdService.js';
import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js';
import { AnnouncementService } from '@/core/AnnouncementService.js';
import { DI } from '@/di-symbols.js';
import { CacheService } from '@/core/CacheService.js';
import { genAid } from '@/misc/id/aid.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import type { TestingModule } from '@nestjs/testing';
import type { MockFunctionMetadata } from 'jest-mock';
const moduleMocker = new ModuleMocker(global);
describe('AnnouncementService', () => {
let app: TestingModule;
let announcementService: AnnouncementService;
let usersRepository: UsersRepository;
let announcementsRepository: AnnouncementsRepository;
let announcementReadsRepository: AnnouncementReadsRepository;
let globalEventService: jest.Mocked<GlobalEventService>;
function createUser(data: Partial<User> = {}) {
const un = secureRndstr(16);
return usersRepository.insert({
id: genAid(new Date()),
createdAt: new Date(),
username: un,
usernameLower: un,
...data,
})
.then(x => usersRepository.findOneByOrFail(x.identifiers[0]));
}
function createAnnouncement(data: Partial<Announcement> = {}) {
return announcementsRepository.insert({
id: genAid(new Date()),
createdAt: new Date(),
updatedAt: null,
title: 'Title',
text: 'Text',
...data,
})
.then(x => announcementsRepository.findOneByOrFail(x.identifiers[0]));
}
beforeEach(async () => {
app = await Test.createTestingModule({
imports: [
GlobalModule,
],
providers: [
AnnouncementEntityService,
AnnouncementService,
CacheService,
IdService,
],
})
.useMocker((token) => {
if (token === GlobalEventService) {
return {
publishMainStream: jest.fn(),
publishBroadcastStream: jest.fn(),
};
}
if (typeof token === 'function') {
const mockMetadata = moduleMocker.getMetadata(token) as MockFunctionMetadata<any, any>;
const Mock = moduleMocker.generateFromMetadata(mockMetadata);
return new Mock();
}
})
.compile();
app.enableShutdownHooks();
announcementService = app.get<AnnouncementService>(AnnouncementService);
usersRepository = app.get<UsersRepository>(DI.usersRepository);
announcementsRepository = app.get<AnnouncementsRepository>(DI.announcementsRepository);
announcementReadsRepository = app.get<AnnouncementReadsRepository>(DI.announcementReadsRepository);
globalEventService = app.get<GlobalEventService>(GlobalEventService) as jest.Mocked<GlobalEventService>;
});
afterEach(async () => {
await Promise.all([
app.get(DI.metasRepository).delete({}),
usersRepository.delete({}),
announcementsRepository.delete({}),
announcementReadsRepository.delete({}),
]);
await app.close();
});
describe('getUnreadAnnouncements', () => {
test('通常', async () => {
const user = await createUser();
const announcement = await createAnnouncement({
title: '1',
});
const result = await announcementService.getUnreadAnnouncements(user);
expect(result.length).toBe(1);
expect(result[0].title).toBe(announcement.title);
});
test('isActiveがfalseは除外', async () => {
const user = await createUser();
await createAnnouncement({
isActive: false,
});
const result = await announcementService.getUnreadAnnouncements(user);
expect(result.length).toBe(0);
});
test('forExistingUsers', async () => {
const user = await createUser();
const [announcementAfter, announcementBefore, announcementBefore2] = await Promise.all([
createAnnouncement({
title: 'after',
createdAt: new Date(),
forExistingUsers: true,
}),
createAnnouncement({
title: 'before',
createdAt: new Date(Date.now() - 1000),
forExistingUsers: true,
}),
createAnnouncement({
title: 'before2',
createdAt: new Date(Date.now() - 1000),
forExistingUsers: false,
}),
]);
const result = await announcementService.getUnreadAnnouncements(user);
expect(result.length).toBe(2);
expect(result.some(a => a.title === announcementAfter.title)).toBe(true);
expect(result.some(a => a.title === announcementBefore.title)).toBe(false);
expect(result.some(a => a.title === announcementBefore2.title)).toBe(true);
});
});
describe('create', () => {
test('通常', async () => {
const result = await announcementService.create({
title: 'Title',
text: 'Text',
});
expect(result.raw.title).toBe('Title');
expect(result.packed.title).toBe('Title');
expect(globalEventService.publishBroadcastStream).toHaveBeenCalled();
expect(globalEventService.publishBroadcastStream.mock.lastCall![0]).toBe('announcementCreated');
expect((globalEventService.publishBroadcastStream.mock.lastCall![1] as any).announcement).toBe(result.packed);
});
test('ユーザー指定', async () => {
const user = await createUser();
const result = await announcementService.create({
title: 'Title',
text: 'Text',
userId: user.id,
});
expect(result.raw.title).toBe('Title');
expect(result.packed.title).toBe('Title');
expect(globalEventService.publishBroadcastStream).not.toHaveBeenCalled();
expect(globalEventService.publishMainStream).toHaveBeenCalled();
expect(globalEventService.publishMainStream.mock.lastCall![0]).toBe(user.id);
expect(globalEventService.publishMainStream.mock.lastCall![1]).toBe('announcementCreated');
expect((globalEventService.publishMainStream.mock.lastCall![2] as any).announcement).toBe(result.packed);
});
});
describe('read', () => {
// TODO
});
});

View file

@ -96,7 +96,6 @@ export async function removeAccount(idOrToken: Account['id']) {
function fetchAccount(token: string, id?: string, forceShowDialog?: boolean): Promise<Account> { function fetchAccount(token: string, id?: string, forceShowDialog?: boolean): Promise<Account> {
return new Promise((done, fail) => { return new Promise((done, fail) => {
// Fetch user
window.fetch(`${apiUrl}/i`, { window.fetch(`${apiUrl}/i`, {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({

View file

@ -7,7 +7,7 @@ import { computed, createApp, watch, markRaw, version as vueVersion, defineAsync
import { common } from './common'; import { common } from './common';
import { version, ui, lang, updateLocale } from '@/config'; import { version, ui, lang, updateLocale } from '@/config';
import { i18n, updateI18n } from '@/i18n'; import { i18n, updateI18n } from '@/i18n';
import { confirm, alert, post, popup, toast, api } from '@/os'; import { confirm, alert, post, popup, toast } from '@/os';
import { useStream } from '@/stream'; import { useStream } from '@/stream';
import * as sound from '@/scripts/sound'; import * as sound from '@/scripts/sound';
import { $i, refreshAccount, login, updateAccount, signout } from '@/account'; import { $i, refreshAccount, login, updateAccount, signout } from '@/account';
@ -83,6 +83,12 @@ export async function mainBoot() {
} }
}); });
for (const announcement of ($i.unreadAnnouncements ?? []).filter(x => x.display === 'dialog')) {
popup(defineAsyncComponent(() => import('@/components/MkAnnouncementDialog.vue')), {
announcement,
}, {}, 'closed');
}
if ($i.isDeleted) { if ($i.isDeleted) {
alert({ alert({
type: 'warning', type: 'warning',
@ -209,6 +215,20 @@ export async function mainBoot() {
updateAccount(i); updateAccount(i);
}); });
main.on('announcementCreated', (ev) => {
const announcement = ev.announcement;
updateAccount({
hasUnreadAnnouncement: true,
unreadAnnouncements: [...($i?.unreadAnnouncements ?? []), announcement],
});
if (announcement.display === 'dialog') {
popup(defineAsyncComponent(() => import('@/components/MkAnnouncementDialog.vue')), {
announcement,
}, {}, 'closed');
}
});
main.on('readAllNotifications', () => { main.on('readAllNotifications', () => {
updateAccount({ hasUnreadNotification: false }); updateAccount({ hasUnreadNotification: false });
}); });
@ -242,8 +262,25 @@ export async function mainBoot() {
sound.play('antenna'); sound.play('antenna');
}); });
stream.on('announcementCreated', (ev) => {
const announcement = ev.announcement;
updateAccount({
hasUnreadAnnouncement: true,
unreadAnnouncements: [...($i?.unreadAnnouncements ?? []), announcement],
});
if (announcement.display === 'dialog') {
popup(defineAsyncComponent(() => import('@/components/MkAnnouncementDialog.vue')), {
announcement,
}, {}, 'closed');
}
});
main.on('readAllAnnouncements', () => { main.on('readAllAnnouncements', () => {
updateAccount({ hasUnreadAnnouncement: false }); updateAccount({
hasUnreadAnnouncement: false,
unreadAnnouncements: [],
});
}); });
// トークンが再生成されたとき // トークンが再生成されたとき
@ -251,11 +288,6 @@ export async function mainBoot() {
main.on('myTokenRegenerated', () => { main.on('myTokenRegenerated', () => {
signout(); signout();
}); });
const unreadUserAnnouncementsList = await api('announcements', { privateOnly: true, withUnreads: true });
if (unreadUserAnnouncementsList.length > 0) {
unreadUserAnnouncementsList.forEach((v) => popup(defineAsyncComponent(() => import('@/components/MkUserAnnouncementModal.vue')), { title: v.title, text: v.text, closeDuration: v.closeDuration, announcementId: v.id }, {}, 'closed'));
}
} }
// shortcut // shortcut

View file

@ -0,0 +1,47 @@
/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { StoryObj } from '@storybook/vue3';
import MkAnnouncementDialog from './MkAnnouncementDialog.vue';
export const Default = {
render(args) {
return {
components: {
MkAnnouncementDialog,
},
setup() {
return {
args,
};
},
computed: {
props() {
return {
...this.args,
};
},
},
template: '<MkAnnouncementDialog v-bind="props" />',
};
},
args: {
announcement: {
id: '1',
title: 'Title',
text: 'Text',
createdAt: new Date().toISOString(),
updatedAt: null,
icon: 'info',
imageUrl: null,
display: 'dialog',
needConfirmationToRead: false,
forYou: true,
},
},
parameters: {
layout: 'centered',
},
} satisfies StoryObj<typeof MkAnnouncementDialog>;

View file

@ -0,0 +1,122 @@
<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<MkModal ref="modal" :zPriority="'middle'" @closed="$emit('closed')" @click="onBgClick">
<div ref="rootEl" :class="$style.root">
<div :class="$style.header">
<span :class="$style.icon">
<i v-if="announcement.icon === 'info'" class="ti ti-info-circle"></i>
<i v-else-if="announcement.icon === 'warning'" class="ti ti-alert-triangle" style="color: var(--warn);"></i>
<i v-else-if="announcement.icon === 'error'" class="ti ti-circle-x" style="color: var(--error);"></i>
<i v-else-if="announcement.icon === 'success'" class="ti ti-check" style="color: var(--success);"></i>
</span>
<Mfm :text="announcement.title"/>
</div>
<div :class="$style.content"><Mfm :text="announcement.text"/></div>
<MkButton :class="$style.gotIt" primary full :disabled="gotItDisabled" @click="gotIt">{{ i18n.ts.gotIt }}<span v-if="secVisible"> ({{ sec }})</span></MkButton>
</div>
</MkModal>
</template>
<script lang="ts" setup>
import { onMounted, ref, shallowRef } from 'vue';
import * as misskey from 'misskey-js';
import * as os from '@/os';
import MkModal from '@/components/MkModal.vue';
import MkButton from '@/components/MkButton.vue';
import { i18n } from '@/i18n';
import { $i, updateAccount } from '@/account';
const props = withDefaults(defineProps<{
announcement: misskey.entities.Announcement;
}>(), {
});
const rootEl = shallowRef<HTMLDivElement>();
const modal = shallowRef<InstanceType<typeof MkModal>>();
const gotItDisabled = ref(true);
const secVisible = ref(true);
const sec = ref(props.announcement.closeDuration);
async function gotIt(): Promise<void> {
if (props.announcement.needConfirmationToRead) {
const confirm = await os.confirm({
type: 'question',
title: i18n.ts._announcement.readConfirmTitle,
text: i18n.t('_announcement.readConfirmText', { title: props.announcement.title }),
});
if (confirm.canceled) return;
}
await os.api('i/read-announcement', { announcementId: props.announcement.id });
if ($i) {
updateAccount({
unreadAnnouncements: $i.unreadAnnouncements.filter((a: { id: string; }) => a.id !== props.announcement.id),
});
}
modal.value?.close();
}
function onBgClick(): void {
if (sec.value > 0) return;
rootEl.value?.animate([{
offset: 0,
transform: 'scale(1)',
}, {
offset: 0.5,
transform: 'scale(1.1)',
}, {
offset: 1,
transform: 'scale(1)',
}], {
duration: 100,
});
}
onMounted(() => {
if (sec.value > 0 ) {
const waitTimer = setInterval(() => {
if (sec.value === 0) {
clearInterval(waitTimer);
gotItDisabled.value = false;
secVisible.value = false;
} else {
gotItDisabled.value = true;
}
sec.value = sec.value - 1;
}, 1000);
} else {
gotItDisabled.value = false;
secVisible.value = false;
}
});
</script>
<style lang="scss" module>
.root {
margin: auto;
position: relative;
padding: 32px;
min-width: 320px;
max-width: 480px;
box-sizing: border-box;
background: var(--panel);
border-radius: var(--radius);
}
.header {
font-size: 120%;
}
.icon {
margin-right: 0.5em;
}
.content {
margin: 1em 0;
}
</style>

View file

@ -172,7 +172,6 @@ import { showMovedDialog } from '@/scripts/show-moved-dialog';
const props = defineProps<{ const props = defineProps<{
note: misskey.entities.Note; note: misskey.entities.Note;
pinned?: boolean;
}>(); }>();
const inChannel = inject('inChannel', null); const inChannel = inject('inChannel', null);

View file

@ -37,7 +37,6 @@ import { userPage } from '@/filters/user';
defineProps<{ defineProps<{
note: misskey.entities.Note; note: misskey.entities.Note;
pinned?: boolean;
}>(); }>();
</script> </script>

View file

@ -31,7 +31,6 @@ import { $i } from '@/account';
const props = defineProps<{ const props = defineProps<{
note: misskey.entities.Note; note: misskey.entities.Note;
pinned?: boolean;
}>(); }>();
const showContent = $ref(false); const showContent = $ref(false);

View file

@ -17,7 +17,12 @@ SPDX-License-Identifier: AGPL-3.0-only
</span> </span>
<span :class="$style.body"> <span :class="$style.body">
<!-- TODO: 無名slotの方は廃止 --> <!-- TODO: 無名slotの方は廃止 -->
<span :class="$style.label" @click="toggle"><slot name="label"></slot><slot></slot></span> <span :class="$style.label">
<span @click="toggle">
<slot name="label"></slot><slot></slot>
</span>
<span v-if="helpText" v-tooltip:dialog="helpText" class="_button _help" :class="$style.help"><i class="ti ti-help-circle"></i></span>
</span>
<p :class="$style.caption"><slot name="caption"></slot></p> <p :class="$style.caption"><slot name="caption"></slot></p>
</span> </span>
</div> </div>
@ -30,6 +35,7 @@ import { i18n } from '@/i18n';
const props = defineProps<{ const props = defineProps<{
modelValue: boolean | Ref<boolean>; modelValue: boolean | Ref<boolean>;
disabled?: boolean; disabled?: boolean;
helpText?: string;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@ -41,10 +47,6 @@ const checked = toRefs(props).modelValue;
const toggle = () => { const toggle = () => {
if (props.disabled) return; if (props.disabled) return;
emit('update:modelValue', !checked.value); emit('update:modelValue', !checked.value);
if (!checked.value) {
}
}; };
</script> </script>
@ -140,4 +142,10 @@ const toggle = () => {
display: none; display: none;
} }
} }
.help {
margin-left: 0.5em;
font-size: 85%;
vertical-align: top;
}
</style> </style>

View file

@ -0,0 +1,169 @@
<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<MkModalWindow
ref="dialog"
:width="800"
:height="600"
:withOkButton="false"
:okButtonDisabled="false"
@close="dialog?.close()"
@closed="$emit('closed')"
>
<template v-if="announcement" #header>:{{ announcement.title }}:</template>
<template v-else #header>New announcement</template>
<div>
<MkSpacer :marginMin="20" :marginMax="28">
<div class="_gaps_m">
<MkInput ref="announceTitleEl" v-model="title" :large="false">
<template #label>{{ i18n.ts.title }}&nbsp;<button v-tooltip="i18n.ts.emoji" :class="['_button']" @click="insertEmoji"><i class="ti ti-mood-happy"></i></button></template>
</MkInput>
<MkTextarea v-model="text">
<template #label>{{ i18n.ts.text }}</template>
</MkTextarea>
<MkRadios v-model="icon">
<template #label>{{ i18n.ts.icon }}</template>
<option value="info"><i class="ti ti-info-circle"></i></option>
<option value="warning"><i class="ti ti-alert-triangle" style="color: var(--warn);"></i></option>
<option value="error"><i class="ti ti-circle-x" style="color: var(--error);"></i></option>
<option value="success"><i class="ti ti-check" style="color: var(--success);"></i></option>
</MkRadios>
<MkRadios v-model="display">
<template #label>{{ i18n.ts.display }}</template>
<option value="normal">{{ i18n.ts.normal }}</option>
<option value="banner">{{ i18n.ts.banner }}</option>
<option value="dialog">{{ i18n.ts.dialog }}</option>
</MkRadios>
<MkSwitch v-model="needConfirmationToRead">
{{ i18n.ts._announcement.needConfirmationToRead }}
<template #caption>{{ i18n.ts._announcement.needConfirmationToReadDescription }}</template>
</MkSwitch>
<MkInput v-model="closeDuration" type="number">
<template #label>{{ i18n.ts.dialogCloseDuration }}</template>
<template #suffix>{{ i18n.ts._time.second }}</template>
</MkInput>
<MkInput v-model="displayOrder" type="number">
<template #label>{{ i18n.ts.displayOrder }}</template>
</MkInput>
<p v-if="readCount">{{ i18n.t('nUsersRead', { n: readCount }) }}</p>
<MkUserCardMini v-if="props.user.id" :user="props.user"></MkUserCardMini>
<MkButton v-if="announcement" danger @click="del()"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton>
</div>
</MkSpacer>
<div :class="$style.footer">
<MkButton primary rounded style="margin: 0 auto;" @click="done"><i class="ti ti-check"></i> {{ props.announcement ? i18n.ts.update : i18n.ts.create }}</MkButton>
</div>
</div>
</MkModalWindow>
</template>
<script lang="ts" setup>
import * as misskey from 'misskey-js';
import * as os from '@/os';
import { i18n } from '@/i18n';
import MkButton from '@/components/MkButton.vue';
import MkInput from '@/components/MkInput.vue';
import MkModalWindow from '@/components/MkModalWindow.vue';
import MkRadios from '@/components/MkRadios.vue';
import MkSwitch from '@/components/MkSwitch.vue';
import MkTextarea from '@/components/MkTextarea.vue';
import MkUserCardMini from '@/components/MkUserCardMini.vue';
const props = defineProps<{
user: misskey.entities.UserLite,
announcement?: any,
}>();
let title: string = $ref(props.announcement ? props.announcement.title : '');
let text: string = $ref(props.announcement ? props.announcement.text : '');
let icon: string = $ref(props.announcement ? props.announcement.icon : 'info');
let display: string = $ref(props.announcement ? props.announcement.display : 'dialog');
let needConfirmationToRead: boolean = $ref(props.announcement ? props.announcement.needConfirmationToRead : false);
let closeDuration: number = $ref(props.announcement ? props.announcement.closeDuration : 0);
let displayOrder: number = $ref(props.announcement ? props.announcement.displayOrder : 0);
let readCount: number = $ref(props.announcement ? props.announcement.readCount : 0);
const emit = defineEmits<{
(ev: 'done', v: { deleted?: boolean; updated?: any; created?: any }): void,
(ev: 'closed'): void
}>();
const dialog = $shallowRef<typeof MkModalWindow | null>(null);
const announceTitleEl = $shallowRef<HTMLInputElement | null>(null);
function insertEmoji(ev: MouseEvent): void {
os.openEmojiPicker((ev.currentTarget ?? ev.target) as HTMLElement, {}, announceTitleEl);
}
async function done(): Promise<void> {
const params = {
title: title,
text: text,
icon: icon,
imageUrl: null,
display: display,
needConfirmationToRead: needConfirmationToRead,
closeDuration: closeDuration,
displayOrder: displayOrder,
readCount: readCount,
userId: props.user.id,
};
if (props.announcement) {
await os.apiWithDialog('admin/announcements/update', {
id: props.announcement.id,
...params,
});
emit('done', {
updated: {
id: props.announcement.id,
...params,
},
});
dialog?.close();
} else {
const created = await os.apiWithDialog('admin/announcements/create', params);
emit('done', {
created: created,
});
dialog?.close();
}
}
async function del(): Promise<void> {
const { canceled } = await os.confirm({
type: 'warning',
text: i18n.t('removeAreYouSure', { x: title }),
});
if (canceled) return;
os.api('admin/announcements/delete', {
id: props.announcement.id,
}).then(() => {
emit('done', {
deleted: true,
});
dialog?.close();
});
}
</script>
<style lang="scss" module>
.footer {
position: sticky;
bottom: 0;
left: 0;
padding: 12px;
border-top: solid 0.5px var(--divider);
-webkit-backdrop-filter: var(--blur, blur(15px));
backdrop-filter: var(--blur, blur(15px));
}
</style>

View file

@ -1,95 +0,0 @@
<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<MkModal ref="modal" :zPriority="'middle'" @click="closeModal" @closed="$emit('closed')">
<div :class="$style.root">
<div :class="$style.title"><Mfm :text="props.title"/></div>
<div :class="$style.text">
<Mfm :text="props.text"/>
</div>
<MkButton :class="$style.gotIt" primary full :disabled="gotItDisabled" @click="gotIt">{{ i18n.ts.gotIt }}<span v-if="secVisible">({{ sec }})</span></MkButton>
</div>
</MkModal>
</template>
<script setup lang="ts">
import { onMounted, ref, shallowRef } from 'vue';
import MkModal from '@/components/MkModal.vue';
import MkButton from '@/components/MkButton.vue';
import { i18n } from '@/i18n';
import { api } from '@/os';
const modal = shallowRef<InstanceType<typeof MkModal>>();
const gotItDisabled = ref(true);
const secVisible = ref(true);
const props = defineProps<{
title: string;
text: string;
announcementId: string | null;
closeDuration: number;
}>();
const sec = ref(props.closeDuration);
async function gotIt() {
gotItDisabled.value = true;
if (props.announcementId) {
await api('i/read-announcement', { announcementId: props.announcementId });
}
modal.value.close();
}
function closeModal() {
if (sec.value === 0) {
modal.value.close();
}
}
onMounted(() => {
if (sec.value > 0 ) {
const waitTimer = setInterval(() => {
if (sec.value === 0) {
clearInterval(waitTimer);
gotItDisabled.value = false;
secVisible.value = false;
} else {
gotItDisabled.value = true;
}
sec.value = sec.value - 1;
}, 1000);
} else {
gotItDisabled.value = false;
secVisible.value = false;
}
});
</script>
<style lang="scss" module>
.root {
margin: auto;
position: relative;
padding: 32px;
min-width: 320px;
max-width: 480px;
box-sizing: border-box;
text-align: center;
background: var(--panel);
border-radius: var(--radius);
}
.title {
font-weight: bold;
}
.text {
margin: 1em 0;
}
.gotIt {
margin: 8px 0 0 0;
}
</style>

View file

@ -7,7 +7,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkStickyContainer> <MkStickyContainer>
<template #header><XHeader :actions="headerActions" :tabs="headerTabs"/></template> <template #header><XHeader :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :contentMax="900"> <MkSpacer :contentMax="900">
<div class="_gaps_m"> <div class="_gaps">
<MkFolder> <MkFolder>
<template #label>{{ i18n.ts.options }}</template> <template #label>{{ i18n.ts.options }}</template>
@ -24,8 +24,18 @@ SPDX-License-Identifier: AGPL-3.0-only
</div> </div>
</MkFolder> </MkFolder>
</MkFolder> </MkFolder>
<section v-for="announcement in announcements" :key="announcement.id">
<div class="_panel _gaps_m" style="padding: 24px;"> <MkFolder v-for="announcement in announcements" :key="announcement.id ?? announcement._id" :defaultOpen="announcement.id == null">
<template #label>{{ announcement.title }}</template>
<template #icon>
<i v-if="announcement.icon === 'info'" class="ti ti-info-circle"></i>
<i v-else-if="announcement.icon === 'warning'" class="ti ti-alert-triangle" style="color: var(--warn);"></i>
<i v-else-if="announcement.icon === 'error'" class="ti ti-circle-x" style="color: var(--error);"></i>
<i v-else-if="announcement.icon === 'success'" class="ti ti-check" style="color: var(--success);"></i>
</template>
<template #caption>{{ announcement.text }}</template>
<div class="_gaps_m">
<MkInput ref="announceTitleEl" v-model="announcement.title" :large="false"> <MkInput ref="announceTitleEl" v-model="announcement.title" :large="false">
<template #label>{{ i18n.ts.title }}&nbsp;<button v-tooltip="i18n.ts.emoji" :class="['_button']" @click="insertEmoji"><i class="ti ti-mood-happy"></i></button></template> <template #label>{{ i18n.ts.title }}&nbsp;<button v-tooltip="i18n.ts.emoji" :class="['_button']" @click="insertEmoji"><i class="ti ti-mood-happy"></i></button></template>
</MkInput> </MkInput>
@ -35,22 +45,42 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkInput v-model="announcement.imageUrl"> <MkInput v-model="announcement.imageUrl">
<template #label>{{ i18n.ts.imageUrl }}</template> <template #label>{{ i18n.ts.imageUrl }}</template>
</MkInput> </MkInput>
<MkInput v-model="announcement.displayOrder" type="number"> <MkRadios v-model="announcement.icon">
<template #label>{{ i18n.ts.displayOrder }}</template> <template #label>{{ i18n.ts.icon }}</template>
</MkInput> <option value="info"><i class="ti ti-info-circle"></i></option>
<option value="warning"><i class="ti ti-alert-triangle" style="color: var(--warn);"></i></option>
<option value="error"><i class="ti ti-circle-x" style="color: var(--error);"></i></option>
<option value="success"><i class="ti ti-check" style="color: var(--success);"></i></option>
</MkRadios>
<MkRadios v-model="announcement.display">
<template #label>{{ i18n.ts.display }}</template>
<option value="normal">{{ i18n.ts.normal }}</option>
<option value="banner">{{ i18n.ts.banner }}</option>
<option value="dialog">{{ i18n.ts.dialog }}</option>
</MkRadios>
<MkSwitch v-model="announcement.forExistingUsers" :helpText="i18n.ts._announcement.forExistingUsersDescription">
{{ i18n.ts._announcement.forExistingUsers }}
</MkSwitch>
<MkSwitch v-model="announcement.needConfirmationToRead" :helpText="i18n.ts._announcement.needConfirmationToReadDescription">
{{ i18n.ts._announcement.needConfirmationToRead }}
</MkSwitch>
<MkInput v-model="announcement.closeDuration" type="number"> <MkInput v-model="announcement.closeDuration" type="number">
<template #label>{{ i18n.ts.dialogCloseDuration }}</template> <template #label>{{ i18n.ts.dialogCloseDuration }}</template>
<template #suffix>{{ i18n.ts._time.second }}</template> <template #suffix>{{ i18n.ts._time.second }}</template>
</MkInput> </MkInput>
<p v-if="announcement.reads">{{ i18n.t('nUsersRead', { n: announcement.reads }) }}</p> <MkInput v-model="announcement.displayOrder" type="number">
<template #label>{{ i18n.ts.displayOrder }}</template>
</MkInput>
<p v-if="announcement.readCount">{{ i18n.t('nUsersRead', { n: announcement.readCount }) }}</p>
<MkUserCardMini v-if="announcement.userId" :user="announcement.user" @click="editUser(announcement)"></MkUserCardMini> <MkUserCardMini v-if="announcement.userId" :user="announcement.user" @click="editUser(announcement)"></MkUserCardMini>
<MkButton v-else class="button" inline primary @click="editUser(announcement)">{{ i18n.ts.specifyUser }}</MkButton> <MkButton v-else class="button" inline primary @click="editUser(announcement)">{{ i18n.ts.specifyUser }}</MkButton>
<div class="buttons _buttons"> <div class="buttons _buttons">
<MkButton class="button" inline primary @click="save(announcement)"><i class="ti ti-device-floppy"></i> {{ i18n.ts.save }}</MkButton> <MkButton v-if="announcement.id == null || announcement.isActive" class="button" inline primary @click="save(announcement)"><i class="ti ti-device-floppy"></i> {{ i18n.ts.save }}</MkButton>
<MkButton class="button" inline danger @click="remove(announcement)"><i class="ti ti-trash"></i> {{ i18n.ts.remove }}</MkButton> <MkButton v-if="announcement.id != null && announcement.isActive" class="button" inline @click="archive(announcement)"><i class="ti ti-check"></i> {{ i18n.ts._announcement.end }} ({{ i18n.ts.archive }})</MkButton>
<MkButton v-if="announcement.id != null" class="button" inline danger @click="del(announcement)"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton>
</div> </div>
</div> </div>
</section> </MkFolder>
<MkButton v-if="hasMore" :class="$style.more" :disabled="!hasMore" primary rounded @click="fetch()">{{ i18n.ts.loadMore }}</MkButton> <MkButton v-if="hasMore" :class="$style.more" :disabled="!hasMore" primary rounded @click="fetch()">{{ i18n.ts.loadMore }}</MkButton>
</div> </div>
</MkSpacer> </MkSpacer>
@ -59,28 +89,26 @@ SPDX-License-Identifier: AGPL-3.0-only
<script lang="ts" setup> <script lang="ts" setup>
import { ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { UserLite } from 'misskey-js/built/entities'; import * as misskey from 'misskey-js';
import XHeader from './_header_.vue'; import XHeader from './_header_.vue';
import MkButton from '@/components/MkButton.vue';
import MkInput from '@/components/MkInput.vue';
import MkTextarea from '@/components/MkTextarea.vue';
import MkFolder from '@/components/MkFolder.vue';
import MkUserCardMini from '@/components/MkUserCardMini.vue';
import * as os from '@/os'; import * as os from '@/os';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata'; import { definePageMetadata } from '@/scripts/page-metadata';
import MkButton from '@/components/MkButton.vue';
import MkFolder from '@/components/MkFolder.vue';
import MkInput from '@/components/MkInput.vue';
import MkRadios from '@/components/MkRadios.vue';
import MkSwitch from '@/components/MkSwitch.vue';
import MkTextarea from '@/components/MkTextarea.vue';
import MkUserCardMini from '@/components/MkUserCardMini.vue';
const announceTitleEl = $shallowRef<HTMLInputElement | null>(null); const announceTitleEl = $shallowRef<HTMLInputElement | null>(null);
const user = ref<UserLite | null>(null); const user = ref<misskey.entities.UserLite | null>(null);
const offset = ref(0); const offset = ref(0);
const hasMore = ref(false); const hasMore = ref(false);
let announcements: any[] = $ref([]); let announcements: any[] = $ref([]);
function insertEmoji(ev: MouseEvent): void {
os.openEmojiPicker(ev.currentTarget ?? ev.target, {}, announceTitleEl);
}
function selectUserFilter(): void { function selectUserFilter(): void {
os.selectUser().then(_user => { os.selectUser().then(_user => {
user.value = _user; user.value = _user;
@ -94,23 +122,30 @@ function editUser(announcement): void {
}); });
} }
function insertEmoji(ev: MouseEvent): void {
os.openEmojiPicker((ev.currentTarget ?? ev.target) as HTMLElement, {}, announceTitleEl);
}
function add(): void { function add(): void {
announcements.unshift({ announcements.unshift({
_id: Math.random().toString(36),
id: null, id: null,
title: '', title: 'New announcement',
text: '', text: '',
imageUrl: null, imageUrl: null,
userId: null, icon: 'info',
user: null, display: 'normal',
forExistingUsers: false,
needConfirmationToRead: false,
closeDuration: 0,
displayOrder: 0, displayOrder: 0,
closeDuration: 10,
}); });
} }
function remove(announcement): void { function del(announcement): void {
os.confirm({ os.confirm({
type: 'warning', type: 'warning',
text: i18n.t('removeAreYouSure', { x: announcement.title }), text: i18n.t('deleteAreYouSure', { x: announcement.title }),
}).then(({ canceled }) => { }).then(({ canceled }) => {
if (canceled) return; if (canceled) return;
announcements = announcements.filter(x => x !== announcement); announcements = announcements.filter(x => x !== announcement);
@ -118,33 +153,21 @@ function remove(announcement): void {
}); });
} }
function save(announcement): void { async function archive(announcement): Promise<void> {
if (announcement.id == null) { await os.apiWithDialog('admin/announcements/update', {
os.api('admin/announcements/create', announcement).then(() => { ...announcement,
os.alert({ isActive: false,
type: 'success',
text: i18n.ts.saved,
}); });
fetch(true); fetch(true);
}).catch(err => { }
os.alert({
type: 'error', async function save(announcement): Promise<void> {
text: err, if (announcement.id == null) {
}); await os.apiWithDialog('admin/announcements/create', announcement);
});
} else { } else {
os.api('admin/announcements/update', announcement).then(() => { await os.apiWithDialog('admin/announcements/update', announcement);
os.alert({
type: 'success',
text: i18n.ts.saved,
});
}).catch(err => {
os.alert({
type: 'error',
text: err,
});
});
} }
fetch(true);
} }
function fetch(resetOffset = false): void { function fetch(resetOffset = false): void {
@ -166,7 +189,7 @@ function fetch(resetOffset = false): void {
} }
watch(user, () => fetch(true)); watch(user, () => fetch(true));
fetch(); fetch(true);
const headerActions = $computed(() => [{ const headerActions = $computed(() => [{
asFullButton: true, asFullButton: true,

View file

@ -5,93 +5,149 @@ SPDX-License-Identifier: AGPL-3.0-only
<template> <template>
<MkStickyContainer> <MkStickyContainer>
<template #header><MkPageHeader :actions="headerActions" :tabs="headerTabs"/></template> <template #header><MkPageHeader v-model:tab="tab" :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :contentMax="800"> <MkSpacer :contentMax="800">
<MkPagination v-slot="{items, reload}" :pagination="pagination" class="ruryvtyk _gaps_m"> <div class="_gaps">
<section v-for="(announcement, i) in items" :key="announcement.id" :class="{ announcement: true, _panel: true, private: announcement.isPrivate }"> <MkInfo v-if="$i && $i.hasUnreadAnnouncement && tab === 'current'" warn>{{ i18n.ts.youHaveUnreadAnnouncements }}</MkInfo>
<div class="header"><span v-if="$i && !announcement.isRead"><span class="ti ti-speakerphone"></span></span><Mfm :text="announcement.title"/></div> <MkPagination ref="paginationEl" :key="tab" v-slot="{items}" :pagination="tab === 'current' ? paginationCurrent : paginationPast" class="_gaps">
<div class="content"> <section v-for="announcement in items" :key="announcement.id" class="_panel" :class="$style.announcement">
<div v-if="announcement.forYou" :class="$style.forYou"><i class="ti ti-pin"></i> {{ i18n.ts.forYou }}</div>
<div :class="$style.header">
<span v-if="$i && !announcement.isRead" style="margin-right: 0.5em;">🆕</span>
<span style="margin-right: 0.5em;">
<i v-if="announcement.icon === 'info'" class="ti ti-info-circle"></i>
<i v-else-if="announcement.icon === 'warning'" class="ti ti-alert-triangle" style="color: var(--warn);"></i>
<i v-else-if="announcement.icon === 'error'" class="ti ti-circle-x" style="color: var(--error);"></i>
<i v-else-if="announcement.icon === 'success'" class="ti ti-check" style="color: var(--success);"></i>
</span>
<Mfm :text="announcement.title"/>
</div>
<div :class="$style.content">
<Mfm :text="announcement.text"/> <Mfm :text="announcement.text"/>
<img v-if="announcement.imageUrl" :src="announcement.imageUrl"/> <img v-if="announcement.imageUrl" :src="announcement.imageUrl"/>
<div style="opacity: 0.7; font-size: 85%;">
<MkTime :time="announcement.updatedAt ?? announcement.createdAt" mode="detail"/>
</div> </div>
<div v-if="$i && !announcement.isRead" class="footer"> </div>
<MkButton primary @click="read(items, reload, announcement, i)"><i class="ti ti-check"></i> {{ i18n.ts.gotIt }}</MkButton> <div v-if="tab !== 'past' && $i && !announcement.isRead" :class="$style.footer">
<MkButton primary @click="read(announcement)"><i class="ti ti-check"></i> {{ i18n.ts.gotIt }}</MkButton>
</div> </div>
</section> </section>
</MkPagination> </MkPagination>
</div>
</MkSpacer> </MkSpacer>
</MkStickyContainer> </MkStickyContainer>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import MkPagination from '@/components/MkPagination.vue'; import { ref, watch } from 'vue';
import MkButton from '@/components/MkButton.vue';
import * as os from '@/os'; import * as os from '@/os';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata'; import { definePageMetadata } from '@/scripts/page-metadata';
import { $i } from '@/account'; import { $i, updateAccount } from '@/account';
import MkPagination from '@/components/MkPagination.vue';
import MkButton from '@/components/MkButton.vue';
import MkInfo from '@/components/MkInfo.vue';
const pagination = { const paginationCurrent = {
endpoint: 'announcements' as const, endpoint: 'announcements' as const,
offsetMode: true, offsetMode: true,
limit: 10, limit: 10,
params: {
isActive: true,
},
}; };
function read(items, reload, announcement, i) { const paginationPast = {
items[i].isRead = true; endpoint: 'announcements' as const,
os.api('i/read-announcement', { offsetMode: true,
announcementId: announcement.id, limit: 10,
}).then(reload); params: {
isActive: false,
},
};
const paginationEl = ref<InstanceType<typeof MkPagination>>();
const tab = ref('current');
async function read(announcement): Promise<void> {
if (announcement.needConfirmationToRead) {
const confirm = await os.confirm({
type: 'question',
title: i18n.ts._announcement.readConfirmTitle,
text: i18n.t('_announcement.readConfirmText', { title: announcement.title }),
});
if (confirm.canceled) return;
}
if (!paginationEl.value) return;
paginationEl.value.updateItem(announcement.id, a => {
a.isRead = true;
return a;
});
await os.api('i/read-announcement', { announcementId: announcement.id });
if ($i) {
updateAccount({
unreadAnnouncements: $i.unreadAnnouncements.filter((a: { id: string; }) => a.id !== announcement.id),
});
}
} }
const headerActions = $computed(() => []); const headerActions = $computed(() => []);
const headerTabs = $computed(() => []); const headerTabs = $computed(() => [{
key: 'current',
title: i18n.ts.currentAnnouncements,
icon: 'ti ti-flare',
}, {
key: 'past',
title: i18n.ts.pastAnnouncements,
icon: 'ti ti-point',
}]);
definePageMetadata({ definePageMetadata({
title: i18n.ts.announcements, title: i18n.ts.announcements,
icon: 'ti ti-speakerphone', icon: 'ti ti-speakerphone',
}); });
const unreadCount = ref($i?.unreadAnnouncements.length ?? 0);
watch(() => $i?.unreadAnnouncements.length ?? 0, () => {
//
if (($i?.unreadAnnouncements.length ?? 0) > unreadCount.value) {
paginationEl.value?.reload();
}
unreadCount.value = $i?.unreadAnnouncements.length ?? 0;
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" module>
.ruryvtyk { .announcement {
> .private {
border-left: 4px solid olivedrab;
}
> .announcement {
padding: 16px; padding: 16px;
}
> .header { .forYou {
display: flex;
align-items: center;
line-height: 24px;
font-size: 90%;
white-space: pre;
color: #d28a3f;
}
.header {
margin-bottom: 16px; margin-bottom: 16px;
font-weight: bold; font-weight: bold;
} }
> .content { .content {
> img { > img {
display: block; display: block;
max-height: 300px; max-height: 300px;
max-width: 100%; max-width: 100%;
} }
}
> .footer {
margin-top: 16px;
}
}
} }
@keyframes fade { .footer {
0% { margin-top: 16px;
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
} }
</style> </style>

View file

@ -80,7 +80,7 @@ SPDX-License-Identifier: AGPL-3.0-only
</MkFolder> </MkFolder>
<MkSwitch v-model="isSensitive">isSensitive</MkSwitch> <MkSwitch v-model="isSensitive">isSensitive</MkSwitch>
<MkSwitch v-model="localOnly">{{ i18n.ts.localOnly }}</MkSwitch> <MkSwitch v-model="localOnly">{{ i18n.ts.localOnly }}</MkSwitch>
<MkButton danger @click="del()"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton> <MkButton v-if="emoji" danger @click="del()"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton>
</div> </div>
</MkSpacer> </MkSpacer>
<div :class="$style.footer"> <div :class="$style.footer">

View file

@ -86,7 +86,7 @@ const tagUsersPagination = $computed(() => ({
endpoint: 'hashtags/users' as const, endpoint: 'hashtags/users' as const,
limit: 30, limit: 30,
params: { params: {
tag: this.tag, tag: props.tag,
origin: 'combined', origin: 'combined',
sort: '+follower', sort: '+follower',
}, },

View file

@ -133,6 +133,31 @@ SPDX-License-Identifier: AGPL-3.0-only
</div> </div>
</MkFolder> </MkFolder>
<MkFolder v-if="user.host == null && iAmModerator">
<template #icon><i class="ti ti-speakerphone"></i></template>
<template #label>{{ i18n.ts.announcements }}</template>
<div class="_gaps">
<MkButton primary rounded @click="createAnnouncement"><i class="ti ti-plus"></i> {{ i18n.ts.new }}</MkButton>
<MkPagination ref="announcementsPaginationEl" :pagination="announcementsPagination">
<template #default="{ items }">
<div class="_gaps_s">
<div v-for="announcement in items" :key="announcement.id" v-panel :class="$style.announcementItem" @click="editAnnouncement(announcement)">
<span style="margin-right: 0.5em;">
<i v-if="announcement.icon === 'info'" class="ti ti-info-circle"></i>
<i v-else-if="announcement.icon === 'warning'" class="ti ti-alert-triangle" style="color: var(--warn);"></i>
<i v-else-if="announcement.icon === 'error'" class="ti ti-circle-x" style="color: var(--error);"></i>
<i v-else-if="announcement.icon === 'success'" class="ti ti-check" style="color: var(--success);"></i>
</span>
<span>{{ announcement.title }}</span>
<span v-if="announcement.reads > 0" style="margin-left: auto; opacity: 0.7;">{{ i18n.ts.messageRead }}</span>
</div>
</div>
</template>
</MkPagination>
</div>
</MkFolder>
<MkFolder> <MkFolder>
<template #icon><i class="ti ti-password"></i></template> <template #icon><i class="ti ti-password"></i></template>
<template #label>IP</template> <template #label>IP</template>
@ -186,28 +211,30 @@ SPDX-License-Identifier: AGPL-3.0-only
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed, watch } from 'vue'; import { computed, defineAsyncComponent, ref, watch } from 'vue';
import * as misskey from 'misskey-js'; import * as misskey from 'misskey-js';
import MkChart from '@/components/MkChart.vue';
import MkObjectView from '@/components/MkObjectView.vue';
import MkTextarea from '@/components/MkTextarea.vue';
import MkSwitch from '@/components/MkSwitch.vue';
import FormLink from '@/components/form/link.vue';
import FormSection from '@/components/form/section.vue';
import MkButton from '@/components/MkButton.vue';
import MkFolder from '@/components/MkFolder.vue';
import MkKeyValue from '@/components/MkKeyValue.vue';
import MkSelect from '@/components/MkSelect.vue';
import FormSuspense from '@/components/form/suspense.vue';
import MkFileListForAdmin from '@/components/MkFileListForAdmin.vue';
import MkInfo from '@/components/MkInfo.vue';
import * as os from '@/os'; import * as os from '@/os';
import { url } from '@/config'; import { url } from '@/config';
import { userPage, acct } from '@/filters/user'; import { userPage, acct } from '@/filters/user';
import { definePageMetadata } from '@/scripts/page-metadata'; import { definePageMetadata } from '@/scripts/page-metadata';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { iAmAdmin, iAmModerator, $i } from '@/account'; import { iAmAdmin, iAmModerator, $i } from '@/account';
import FormLink from '@/components/form/link.vue';
import FormSection from '@/components/form/section.vue';
import FormSuspense from '@/components/form/suspense.vue';
import MkButton from '@/components/MkButton.vue';
import MkChart from '@/components/MkChart.vue';
import MkFileListForAdmin from '@/components/MkFileListForAdmin.vue';
import MkFolder from '@/components/MkFolder.vue';
import MkInfo from '@/components/MkInfo.vue';
import MkKeyValue from '@/components/MkKeyValue.vue';
import MkObjectView from '@/components/MkObjectView.vue';
import MkPagination from '@/components/MkPagination.vue';
import MkRolePreview from '@/components/MkRolePreview.vue'; import MkRolePreview from '@/components/MkRolePreview.vue';
import MkSelect from '@/components/MkSelect.vue';
import MkSwitch from '@/components/MkSwitch.vue';
import MkTextarea from '@/components/MkTextarea.vue';
import { updateColumn } from '@/ui/deck/deck-store';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
userId: string; userId: string;
@ -235,6 +262,15 @@ const filesPagination = {
userId: props.userId, userId: props.userId,
})), })),
}; };
const announcementsPaginationEl = ref<InstanceType<typeof MkPagination>>();
const announcementsPagination = {
endpoint: 'admin/announcements/list' as const,
offsetMode: true,
limit: 10,
params: computed(() => ({
userId: props.userId,
})),
};
let expandedRoles = $ref([]); let expandedRoles = $ref([]);
function createFetcher() { function createFetcher() {
@ -409,6 +445,27 @@ function toggleRoleItem(role) {
} }
} }
function createAnnouncement(): void {
os.popup(defineAsyncComponent(() => import('@/components/MkUserAnnouncementEditDialog.vue')), {
user,
}, {
done: async () => {
announcementsPaginationEl.value?.reload();
},
}, 'closed');
}
function editAnnouncement(announcement): void {
os.popup(defineAsyncComponent(() => import('@/components/MkUserAnnouncementEditDialog.vue')), {
user,
announcement,
}, {
done: async () => {
announcementsPaginationEl.value?.reload();
},
}, 'closed');
}
watch(() => props.userId, () => { watch(() => props.userId, () => {
init = createFetcher(); init = createFetcher();
}, { }, {
@ -577,4 +634,11 @@ definePageMetadata(computed(() => ({
margin-left: 8px; margin-left: 8px;
align-self: center; align-self: center;
} }
.announcementItem {
display: flex;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
}
</style> </style>

View file

@ -0,0 +1,80 @@
<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<div :class="$style.root">
<MkA
v-for="announcement in $i.unreadAnnouncements.filter(x => x.display === 'banner')"
:key="announcement.id"
:class="$style.item"
to="/announcements"
>
<span :class="$style.icon">
<i v-if="announcement.icon === 'info'" class="ti ti-info-circle"></i>
<i v-else-if="announcement.icon === 'warning'" class="ti ti-alert-triangle" style="color: var(--warn);"></i>
<i v-else-if="announcement.icon === 'error'" class="ti ti-circle-x" style="color: var(--error);"></i>
<i v-else-if="announcement.icon === 'success'" class="ti ti-check" style="color: var(--success);"></i>
</span>
<span :class="$style.title">{{ announcement.title }}</span>
<span :class="$style.body">{{ announcement.text }}</span>
</MkA>
</div>
</template>
<script lang="ts" setup>
import { $i } from '@/account';
</script>
<style lang="scss" module>
.root {
font-size: 15px;
background: var(--panel);
}
.item {
--height: 24px;
font-size: 0.85em;
display: flex;
vertical-align: bottom;
width: 100%;
line-height: var(--height);
height: var(--height);
overflow: clip;
contain: strict;
background: var(--accent);
color: var(--fgOnAccent);
@container (max-width: 1000px) {
display: block;
text-align: center;
> .body {
display: none;
}
}
}
.icon {
margin-left: 10px;
}
.title {
padding: 0 10px;
font-weight: bold;
&:empty {
display: none;
}
}
.body {
min-width: 0;
flex: 1;
overflow: clip;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>

View file

@ -8,6 +8,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<XSidebar v-if="!isMobile"/> <XSidebar v-if="!isMobile"/>
<div :class="$style.main"> <div :class="$style.main">
<XAnnouncements v-if="$i" :class="$style.announcements"/>
<XStatusBars/> <XStatusBars/>
<div ref="columnsEl" :class="[$style.sections, { [$style.center]: deckStore.reactiveState.columnAlign.value === 'center', [$style.snapScroll]: snapScroll }]" @contextmenu.self.prevent="onContextmenu" @wheel.self="onWheel"> <div ref="columnsEl" :class="[$style.sections, { [$style.center]: deckStore.reactiveState.columnAlign.value === 'center', [$style.snapScroll]: snapScroll }]" @contextmenu.self.prevent="onContextmenu" @wheel.self="onWheel">
<!-- sectionを利用しているのはdeck.vue側でcolumnに対してfirst-of-typeを効かせるため --> <!-- sectionを利用しているのはdeck.vue側でcolumnに対してfirst-of-typeを効かせるため -->
@ -113,6 +114,7 @@ import XMentionsColumn from '@/ui/deck/mentions-column.vue';
import XDirectColumn from '@/ui/deck/direct-column.vue'; import XDirectColumn from '@/ui/deck/direct-column.vue';
import XRoleTimelineColumn from '@/ui/deck/role-timeline-column.vue'; import XRoleTimelineColumn from '@/ui/deck/role-timeline-column.vue';
const XStatusBars = defineAsyncComponent(() => import('@/ui/_common_/statusbars.vue')); const XStatusBars = defineAsyncComponent(() => import('@/ui/_common_/statusbars.vue'));
const XAnnouncements = defineAsyncComponent(() => import('@/ui/_common_/announcements.vue'));
const columnComponents = { const columnComponents = {
main: XMainColumn, main: XMainColumn,

View file

@ -8,7 +8,12 @@ SPDX-License-Identifier: AGPL-3.0-only
<XSidebar v-if="!isMobile" :class="$style.sidebar"/> <XSidebar v-if="!isMobile" :class="$style.sidebar"/>
<MkStickyContainer ref="contents" :class="$style.contents" style="container-type: inline-size;" @contextmenu.stop="onContextmenu"> <MkStickyContainer ref="contents" :class="$style.contents" style="container-type: inline-size;" @contextmenu.stop="onContextmenu">
<template #header><XStatusBars :class="$style.statusbars"/></template> <template #header>
<div>
<XAnnouncements v-if="$i" :class="$style.announcements"/>
<XStatusBars :class="$style.statusbars"/>
</div>
</template>
<RouterView/> <RouterView/>
<div :class="$style.spacer"></div> <div :class="$style.spacer"></div>
</MkStickyContainer> </MkStickyContainer>
@ -105,6 +110,7 @@ import { useScrollPositionManager } from '@/nirax';
const XWidgets = defineAsyncComponent(() => import('./universal.widgets.vue')); const XWidgets = defineAsyncComponent(() => import('./universal.widgets.vue'));
const XSidebar = defineAsyncComponent(() => import('@/ui/_common_/navbar.vue')); const XSidebar = defineAsyncComponent(() => import('@/ui/_common_/navbar.vue'));
const XStatusBars = defineAsyncComponent(() => import('@/ui/_common_/statusbars.vue')); const XStatusBars = defineAsyncComponent(() => import('@/ui/_common_/statusbars.vue'));
const XAnnouncements = defineAsyncComponent(() => import('@/ui/_common_/announcements.vue'));
const DESKTOP_THRESHOLD = 1100; const DESKTOP_THRESHOLD = 1100;
const MOBILE_THRESHOLD = 500; const MOBILE_THRESHOLD = 500;

View file

@ -30,9 +30,13 @@ type Announcement = {
text: string; text: string;
title: string; title: string;
imageUrl: string | null; imageUrl: string | null;
isRead?: boolean; display: 'normal' | 'banner' | 'dialog';
isPrivate: boolean; icon: 'info' | 'warning' | 'error' | 'success';
needConfirmationToRead: boolean;
closeDuration: number; closeDuration: number;
displayOrder: number;
forYou: boolean;
isRead?: boolean;
}; };
// @public (undocumented) // @public (undocumented)
@ -566,11 +570,9 @@ export type Endpoints = {
}; };
'announcements': { 'announcements': {
req: { req: {
isActive?: boolean;
limit?: number; limit?: number;
withUnreads?: boolean; offset?: number;
sinceId?: Announcement['id'];
untilId?: Announcement['id'];
privateOnly?: boolean;
}; };
res: Announcement[]; res: Announcement[];
}; };
@ -2476,6 +2478,7 @@ type MeDetailed = UserDetailed & {
noCrawle: boolean; noCrawle: boolean;
receiveAnnouncementEmail: boolean; receiveAnnouncementEmail: boolean;
usePasswordLessLogin: boolean; usePasswordLessLogin: boolean;
unreadAnnouncements: Announcement[];
[other: string]: any; [other: string]: any;
}; };

View file

@ -77,7 +77,7 @@ export type Endpoints = {
'admin/relays/remove': { req: TODO; res: TODO; }; 'admin/relays/remove': { req: TODO; res: TODO; };
// announcements // announcements
'announcements': { req: { limit?: number; withUnreads?: boolean; sinceId?: Announcement['id']; untilId?: Announcement['id']; privateOnly?: boolean; }; res: Announcement[]; }; 'announcements': { req: { isActive?: boolean; limit?: number; offset?: number; }; res: Announcement[]; };
// antennas // antennas
'antennas/create': { req: TODO; res: Antenna; }; 'antennas/create': { req: TODO; res: Antenna; };

View file

@ -106,6 +106,7 @@ export type MeDetailed = UserDetailed & {
noCrawle: boolean; noCrawle: boolean;
receiveAnnouncementEmail: boolean; receiveAnnouncementEmail: boolean;
usePasswordLessLogin: boolean; usePasswordLessLogin: boolean;
unreadAnnouncements: Announcement[];
[other: string]: any; [other: string]: any;
}; };
@ -418,9 +419,13 @@ export type Announcement = {
text: string; text: string;
title: string; title: string;
imageUrl: string | null; imageUrl: string | null;
isRead?: boolean; display: 'normal' | 'banner' | 'dialog';
isPrivate: boolean; icon: 'info' | 'warning' | 'error' | 'success';
needConfirmationToRead: boolean;
closeDuration: number; closeDuration: number;
displayOrder: number;
forYou: boolean;
isRead?: boolean;
}; };
export type Antenna = { export type Antenna = {