Skip to content

Commit

Permalink
enhance: 招待機能の改善 (#11195)
Browse files Browse the repository at this point in the history
* refactor(backend): 招待機能を改修

* feat(backend): 招待コードのcreate/delete/listエンドポイントを追加

* add(misskey-js): エンドポイントと型を追加

* change(backend): metaでinvite関連の情報も返すように

* add(misskey-js): エンドポイントと型を追加

* add(backend): `/endpoints/invite/limit`を追加

* fix: createdByがnullableではなかったのを修正

* fix: relationが取得できていなかった問題を修正

* fix: パラメータを間違えていたのを修正

* feat(client): 招待ページを実装

* change(client): インスタンスメニューの「招待」押した場合に招待ページに飛ぶように変更

* feat: 招待コードをコピーできるように

* change(backend): metaに招待コード発行に関する情報を持たせるのをやめる

* feat: ロールごとに招待コードの発行上限数などを設定できるように

* change(client): 招待コードをコピーしたときにダイアログを出すように

* add: 招待に関する管理者用のエンドポイントを追加

* change(backend): モデレーターであれば作成者以外でも招待コードを削除できるように

* change(backend): admin/invite/listはオフセットでページネーションするように

* feat(client): 招待コードの管理ページを追加

* feat(client): 招待コードのリストをソートできるように

* change: `admin/invite/create`のレスポンスを修正

* fix(client): 有効期限を指定できていなかった問題を修正

* refactor: 必要のない箇所を削除

* perf(backend): use limit() instead of take()

* change(client): 作成ボタンを見た目を変更

* refactor: 招待コードの生成部分を共通化し、コード内に"01OI"のいずれかの文字を含まないように

* fix(client): paginationの仕様が変わっていたので修正

* change(backend): expiresAtパラメータのnullを許容

* change(client): 有効期限を設けないときは日付の入力欄を非表示に

* fix: 自身のポリシーよりもインスタンス側のポリシーが優先表示される問題を修正

* fix: n時間のときに「n時間間」となってしまうのを修正

* fix(backend): ポリシーが途中で変更されたときに作成可能数がマイナス表記になってしまうのを修正

* change(client): 招待コードのユーザー名が不明な理由を表示するように

* update: CHANGELOG.md

* lint

* refactor

* refactor

* tweak ui

* 🎨

* 🎨

* add(backend): indexを追加

* change(backend): indexの追加に伴う変更

* change(client): インスタンスメニューの「招待」の場所を変更

* add(frontend): MkInviteCode用のstorybookを追加

* Update misskey-js.api.md

* fix(misskey-js): InviteのcreatedByの型が間違っていたのを修正

---------

Co-authored-by: syuilo <[email protected]>
Co-authored-by: tamaina <[email protected]>
  • Loading branch information
3 people authored Jul 15, 2023
1 parent 1c82e97 commit 02957a1
Show file tree
Hide file tree
Showing 36 changed files with 1,341 additions and 56 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
### General
- identicon生成を無効にしてパフォーマンスを向上させることができるようになりました
- サーバーのマシン情報の公開を無効にしてパフォーマンスを向上させることができるようになりました
- 招待機能を改善しました
* 過去に発行した招待コードを確認できるようになりました
* ロールごとに招待コードの発行数制限と制限対象期間、有効期限を設定できるようになりました
* 招待コードを作成したユーザーと使用したユーザーを確認できるようになりました

### Client
- deck UIのカラムのメニューからアンテナとリストの編集画面を開けるように
Expand Down
20 changes: 20 additions & 0 deletions locales/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,23 @@ export interface Locale {
"enableServerMachineStats": string;
"enableIdenticonGeneration": string;
"turnOffToImprovePerformance": string;
"createInviteCode": string;
"createWithOptions": string;
"createCount": string;
"inviteCodeCreated": string;
"inviteLimitExceeded": string;
"createLimitRemaining": string;
"inviteLimitResetCycle": string;
"expirationDate": string;
"noExpirationDate": string;
"inviteCodeUsedAt": string;
"registeredUserUsingInviteCode": string;
"waitingForMailAuth": string;
"inviteCodeCreator": string;
"usedAt": string;
"unused": string;
"used": string;
"expired": string;
"_initialAccountSetting": {
"accountCreated": string;
"letsStartAccountSetup": string;
Expand Down Expand Up @@ -1465,6 +1482,9 @@ export interface Locale {
"ltlAvailable": string;
"canPublicNote": string;
"canInvite": string;
"inviteLimit": string;
"inviteLimitCycle": string;
"inviteExpirationTime": string;
"canManageCustomEmojis": string;
"driveCapacity": string;
"alwaysMarkNsfw": string;
Expand Down
20 changes: 20 additions & 0 deletions locales/ja-JP.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,23 @@ branding: "ブランディング"
enableServerMachineStats: "サーバーのマシン情報を公開する"
enableIdenticonGeneration: "ユーザーごとのIdenticon生成を有効にする"
turnOffToImprovePerformance: "オフにするとパフォーマンスが向上します。"
createInviteCode: "招待コードを作成"
createWithOptions: "オプションを指定して作成"
createCount: "作成数"
inviteCodeCreated: "招待コードを作成しました"
inviteLimitExceeded: "作成できる招待コードの数が上限に達しています。"
createLimitRemaining: "作成できる招待コード: 残り {limit} 個"
inviteLimitResetCycle: "{time}で最大 {limit} 個の招待コードを作成できます。"
expirationDate: "有効期限"
noExpirationDate: "有効期限を設けない"
inviteCodeUsedAt: "招待コードが使用された日時"
registeredUserUsingInviteCode: "招待コードを使用したユーザー"
waitingForMailAuth: "メール認証待ち"
inviteCodeCreator: "招待コードを作成したユーザー"
usedAt: "使用日時"
unused: "未使用"
used: "使用済み"
expired: "期限切れ"

_initialAccountSetting:
accountCreated: "アカウントの作成が完了しました!"
Expand Down Expand Up @@ -1387,6 +1404,9 @@ _role:
ltlAvailable: "ローカルタイムラインの閲覧"
canPublicNote: "パブリック投稿の許可"
canInvite: "サーバー招待コードの発行"
inviteLimit: "招待コードの作成可能数"
inviteLimitCycle: "招待コードの発行間隔"
inviteExpirationTime: "招待コードの有効期限"
canManageCustomEmojis: "カスタム絵文字の管理"
driveCapacity: "ドライブ容量"
alwaysMarkNsfw: "ファイルにNSFWを常に付与"
Expand Down
25 changes: 25 additions & 0 deletions packages/backend/migration/1688720440658-refactor-invite-system.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export class RefactorInviteSystem1688720440658 {
name = 'RefactorInviteSystem1688720440658'

async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD "expiresAt" TIMESTAMP WITH TIME ZONE`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD "usedAt" TIMESTAMP WITH TIME ZONE`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD "pendingUserId" character varying(32)`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD "createdById" character varying(32)`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD "usedById" character varying(32)`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD CONSTRAINT "UQ_b6f93f2f30bdbb9a5ebdc7c7189" UNIQUE ("usedById")`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD CONSTRAINT "FK_beba993576db0261a15364ea96e" FOREIGN KEY ("createdById") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "registration_ticket" ADD CONSTRAINT "FK_b6f93f2f30bdbb9a5ebdc7c7189" FOREIGN KEY ("usedById") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}

async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP CONSTRAINT "FK_b6f93f2f30bdbb9a5ebdc7c7189"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP CONSTRAINT "FK_beba993576db0261a15364ea96e"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP CONSTRAINT "UQ_b6f93f2f30bdbb9a5ebdc7c7189"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP COLUMN "usedById"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP COLUMN "createdById"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP COLUMN "pendingUserId"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP COLUMN "usedAt"`);
await queryRunner.query(`ALTER TABLE "registration_ticket" DROP COLUMN "expiresAt"`);
}
}
13 changes: 13 additions & 0 deletions packages/backend/migration/1688880985544-add-index-to-relations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class AddIndexToRelations1688880985544 {
name = 'AddIndexToRelations1688880985544'

async up(queryRunner) {
await queryRunner.query(`CREATE INDEX "IDX_beba993576db0261a15364ea96" ON "registration_ticket" ("createdById") `);
await queryRunner.query(`CREATE INDEX "IDX_b6f93f2f30bdbb9a5ebdc7c718" ON "registration_ticket" ("usedById") `);
}

async down(queryRunner) {
await queryRunner.query(`DROP INDEX "public"."IDX_b6f93f2f30bdbb9a5ebdc7c718"`);
await queryRunner.query(`DROP INDEX "public"."IDX_beba993576db0261a15364ea96"`);
}
}
6 changes: 6 additions & 0 deletions packages/backend/src/core/CoreModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import { GalleryLikeEntityService } from './entities/GalleryLikeEntityService.js
import { GalleryPostEntityService } from './entities/GalleryPostEntityService.js';
import { HashtagEntityService } from './entities/HashtagEntityService.js';
import { InstanceEntityService } from './entities/InstanceEntityService.js';
import { InviteCodeEntityService } from './entities/InviteCodeEntityService.js';
import { ModerationLogEntityService } from './entities/ModerationLogEntityService.js';
import { MutingEntityService } from './entities/MutingEntityService.js';
import { RenoteMutingEntityService } from './entities/RenoteMutingEntityService.js';
Expand Down Expand Up @@ -205,6 +206,7 @@ const $GalleryLikeEntityService: Provider = { provide: 'GalleryLikeEntityService
const $GalleryPostEntityService: Provider = { provide: 'GalleryPostEntityService', useExisting: GalleryPostEntityService };
const $HashtagEntityService: Provider = { provide: 'HashtagEntityService', useExisting: HashtagEntityService };
const $InstanceEntityService: Provider = { provide: 'InstanceEntityService', useExisting: InstanceEntityService };
const $InviteCodeEntityService: Provider = { provide: 'InviteCodeEntityService', useExisting: InviteCodeEntityService };
const $ModerationLogEntityService: Provider = { provide: 'ModerationLogEntityService', useExisting: ModerationLogEntityService };
const $MutingEntityService: Provider = { provide: 'MutingEntityService', useExisting: MutingEntityService };
const $RenoteMutingEntityService: Provider = { provide: 'RenoteMutingEntityService', useExisting: RenoteMutingEntityService };
Expand Down Expand Up @@ -329,6 +331,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
GalleryPostEntityService,
HashtagEntityService,
InstanceEntityService,
InviteCodeEntityService,
ModerationLogEntityService,
MutingEntityService,
RenoteMutingEntityService,
Expand Down Expand Up @@ -448,6 +451,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$GalleryPostEntityService,
$HashtagEntityService,
$InstanceEntityService,
$InviteCodeEntityService,
$ModerationLogEntityService,
$MutingEntityService,
$RenoteMutingEntityService,
Expand Down Expand Up @@ -567,6 +571,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
GalleryPostEntityService,
HashtagEntityService,
InstanceEntityService,
InviteCodeEntityService,
ModerationLogEntityService,
MutingEntityService,
RenoteMutingEntityService,
Expand Down Expand Up @@ -685,6 +690,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$GalleryPostEntityService,
$HashtagEntityService,
$InstanceEntityService,
$InviteCodeEntityService,
$ModerationLogEntityService,
$MutingEntityService,
$RenoteMutingEntityService,
Expand Down
9 changes: 9 additions & 0 deletions packages/backend/src/core/RoleService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export type RolePolicies = {
ltlAvailable: boolean;
canPublicNote: boolean;
canInvite: boolean;
inviteLimit: number;
inviteLimitCycle: number;
inviteExpirationTime: number;
canManageCustomEmojis: boolean;
canSearchNotes: boolean;
canHideAds: boolean;
Expand All @@ -42,6 +45,9 @@ export const DEFAULT_POLICIES: RolePolicies = {
ltlAvailable: true,
canPublicNote: true,
canInvite: false,
inviteLimit: 0,
inviteLimitCycle: 60 * 24 * 7,
inviteExpirationTime: 0,
canManageCustomEmojis: false,
canSearchNotes: false,
canHideAds: false,
Expand Down Expand Up @@ -277,6 +283,9 @@ export class RoleService implements OnApplicationShutdown {
ltlAvailable: calc('ltlAvailable', vs => vs.some(v => v === true)),
canPublicNote: calc('canPublicNote', vs => vs.some(v => v === true)),
canInvite: calc('canInvite', vs => vs.some(v => v === true)),
inviteLimit: calc('inviteLimit', vs => Math.max(...vs)),
inviteLimitCycle: calc('inviteLimitCycle', vs => Math.max(...vs)),
inviteExpirationTime: calc('inviteExpirationTime', vs => Math.max(...vs)),
canManageCustomEmojis: calc('canManageCustomEmojis', vs => vs.some(v => v === true)),
canSearchNotes: calc('canSearchNotes', vs => vs.some(v => v === true)),
canHideAds: calc('canHideAds', vs => vs.some(v => v === true)),
Expand Down
52 changes: 52 additions & 0 deletions packages/backend/src/core/entities/InviteCodeEntityService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
import type { RegistrationTicketsRepository } from '@/models/index.js';
import { awaitAll } from '@/misc/prelude/await-all.js';
import type { Packed } from '@/misc/json-schema.js';
import type { User } from '@/models/entities/User.js';
import type { RegistrationTicket } from '@/models/entities/RegistrationTicket.js';
import { bindThis } from '@/decorators.js';
import { UserEntityService } from './UserEntityService.js';

@Injectable()
export class InviteCodeEntityService {
constructor(
@Inject(DI.registrationTicketsRepository)
private registrationTicketsRepository: RegistrationTicketsRepository,

private userEntityService: UserEntityService,
) {
}

@bindThis
public async pack(
src: RegistrationTicket['id'] | RegistrationTicket,
me?: { id: User['id'] } | null | undefined,
): Promise<Packed<'InviteCode'>> {
const target = typeof src === 'object' ? src : await this.registrationTicketsRepository.findOneOrFail({
where: {
id: src,
},
relations: ['createdBy', 'usedBy'],
});

return await awaitAll({
id: target.id,
code: target.code,
expiresAt: target.expiresAt ? target.expiresAt.toISOString() : null,
createdAt: target.createdAt.toISOString(),
createdBy: target.createdBy ? await this.userEntityService.pack(target.createdBy, me) : null,
usedBy: target.usedBy ? await this.userEntityService.pack(target.usedBy, me) : null,
usedAt: target.usedAt ? target.usedAt.toISOString() : null,
used: !!target.usedAt,
});
}

@bindThis
public packMany(
targets: any[],
me: { id: User['id'] },
) {
return Promise.all(targets.map(x => this.pack(x, me)));
}
}
20 changes: 20 additions & 0 deletions packages/backend/src/misc/generate-invite-code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { secureRndstr } from './secure-rndstr.js';

const CHARS = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // [0-9A-Z] w/o [01IO] (32 patterns)

export function generateInviteCode(): string {
const code = secureRndstr(8, {
chars: CHARS,
});

const uniqueId = [];
let n = Math.floor(Date.now() / 1000 / 60);
while (true) {
uniqueId.push(CHARS[n % CHARS.length]);
const t = Math.floor(n / CHARS.length);
if (!t) break;
n = t;
}

return code + uniqueId.reverse().join('');
}
2 changes: 2 additions & 0 deletions packages/backend/src/misc/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { packedRenoteMutingSchema } from '@/models/json-schema/renote-muting.js'
import { packedBlockingSchema } from '@/models/json-schema/blocking.js';
import { packedNoteReactionSchema } from '@/models/json-schema/note-reaction.js';
import { packedHashtagSchema } from '@/models/json-schema/hashtag.js';
import { packedInviteCodeSchema } from '@/models/json-schema/invite-code.js';
import { packedPageSchema } from '@/models/json-schema/page.js';
import { packedNoteFavoriteSchema } from '@/models/json-schema/note-favorite.js';
import { packedChannelSchema } from '@/models/json-schema/channel.js';
Expand Down Expand Up @@ -52,6 +53,7 @@ export const refs = {
RenoteMuting: packedRenoteMutingSchema,
Blocking: packedBlockingSchema,
Hashtag: packedHashtagSchema,
InviteCode: packedInviteCodeSchema,
Page: packedPageSchema,
Channel: packedChannelSchema,
QueueCount: packedQueueCountSchema,
Expand Down
51 changes: 47 additions & 4 deletions packages/backend/src/models/entities/RegistrationTicket.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,60 @@
import { PrimaryColumn, Entity, Index, Column } from 'typeorm';
import { PrimaryColumn, Entity, Index, Column, ManyToOne, JoinColumn, OneToOne } from 'typeorm';
import { id } from '../id.js';
import { User } from './User.js';

@Entity()
export class RegistrationTicket {
@PrimaryColumn(id())
public id: string;

@Column('timestamp with time zone')
public createdAt: Date;

@Index({ unique: true })
@Column('varchar', {
length: 64,
})
public code: string;

@Column('timestamp with time zone', {
nullable: true,
})
public expiresAt: Date | null;

@Column('timestamp with time zone')
public createdAt: Date;

@ManyToOne(type => User, {
onDelete: 'CASCADE',
})
@JoinColumn()
public createdBy: User | null;

@Index()
@Column({
...id(),
nullable: true,
})
public createdById: User['id'] | null;

@OneToOne(type => User, {
onDelete: 'CASCADE',
})
@JoinColumn()
public usedBy: User | null;

@Index()
@Column({
...id(),
nullable: true,
})
public usedById: User['id'] | null;

@Column('timestamp with time zone', {
nullable: true,
})
public usedAt: Date | null;

@Column('varchar', {
length: 32,
nullable: true,
})
public pendingUserId: string | null;
}
45 changes: 45 additions & 0 deletions packages/backend/src/models/json-schema/invite-code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export const packedInviteCodeSchema = {
type: 'object',
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'id',
example: 'xxxxxxxxxx',
},
code: {
type: 'string',
optional: false, nullable: false,
example: 'GR6S02ERUA5VR',
},
expiresAt: {
type: 'string',
optional: false, nullable: true,
format: 'date-time',
},
createdAt: {
type: 'string',
optional: false, nullable: false,
format: 'date-time',
},
createdBy: {
type: 'object',
optional: false, nullable: true,
ref: 'UserLite',
},
usedBy: {
type: 'object',
optional: false, nullable: true,
ref: 'UserLite',
},
usedAt: {
type: 'string',
optional: false, nullable: true,
format: 'date-time',
},
used: {
type: 'boolean',
optional: false, nullable: false,
},
},
} as const;
Loading

1 comment on commit 02957a1

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chromatic detects changes. Please review the changes on Chromatic.

Please sign in to comment.