diff --git a/.config/ci.yml b/.config/ci.yml index c48fca49bf..c381d21d92 100644 --- a/.config/ci.yml +++ b/.config/ci.yml @@ -6,7 +6,7 @@ #───┘ URL └───────────────────────────────────────────────────── # Final accessible URL seen by a user. -url: https://example.tld/ +url: http://misskey.local # ONCE YOU HAVE STARTED THE INSTANCE, DO NOT CHANGE THE # URL SETTINGS AFTER THAT! diff --git a/.config/docker_example.yml b/.config/docker_example.yml index 296237c95d..c22bd83c2e 100644 --- a/.config/docker_example.yml +++ b/.config/docker_example.yml @@ -163,7 +163,7 @@ redis: # ┌───────────────────────────┐ #───┘ MeiliSearch configuration └───────────────────────────── -# You can set scope to local (default value) or global +# You can set scope to local (default value) or global # (include notes from remote). #meilisearch: @@ -193,6 +193,21 @@ redis: id: 'aidx' +# ┌────────────────┐ +#───┘ Error tracking └────────────────────────────────────────── + +# Sentry is available for error tracking. +# See the Sentry documentation for more details on options. + +#sentryForBackend: +# enableNodeProfiling: true +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + +#sentryForFrontend: +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + # ┌─────────────────────┐ #───┘ Other configuration └───────────────────────────────────── @@ -261,7 +276,7 @@ signToActivityPubGet: true checkActivityPubGetSignature: false # For security reasons, uploading attachments from the intranet is prohibited, -# but exceptions can be made from the following settings. Default value is "undefined". +# but exceptions can be made from the following settings. Default value is "undefined". # Read changelog to learn more (Improvements of 12.90.0 (2021/09/04)). #allowedPrivateNetworks: [ # '127.0.0.1/32' diff --git a/.config/example.yml b/.config/example.yml index c82e744ee1..ae55b983bb 100644 --- a/.config/example.yml +++ b/.config/example.yml @@ -38,7 +38,7 @@ # Option 3: If neither of the above applies to you. # (In this case, the source code should be published # on the Misskey interface. IT IS NOT ENOUGH TO -# DISCLOSE THE SOURCE CODE WEHN A USER REQUESTS IT BY +# DISCLOSE THE SOURCE CODE WHEN A USER REQUESTS IT BY # E-MAIL OR OTHER MEANS. If you are not satisfied # with this, it is recommended that you read the # license again carefully. Anyway, enabling this @@ -205,6 +205,21 @@ redis: id: 'aidx' +# ┌────────────────┐ +#───┘ Error tracking └────────────────────────────────────────── + +# Sentry is available for error tracking. +# See the Sentry documentation for more details on options. + +#sentryForBackend: +# enableNodeProfiling: true +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + +#sentryForFrontend: +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + # ┌─────────────────────┐ #───┘ Other configuration └───────────────────────────────────── diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index e409adf644..31b6212cb5 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -4,12 +4,10 @@ "service": "app", "workspaceFolder": "/workspace", "features": { - "ghcr.io/devcontainers-contrib/features/pnpm:2": { - "version": "8.9.2" - }, "ghcr.io/devcontainers/features/node:1": { - "version": "20.10.0" - } + "version": "20.12.2" + }, + "ghcr.io/devcontainers-contrib/features/corepack:1": {} }, "forwardPorts": [3000], "postCreateCommand": "sudo chmod 755 .devcontainer/init.sh && .devcontainer/init.sh", @@ -19,7 +17,6 @@ "editorconfig.editorconfig", "dbaeumer.vscode-eslint", "Vue.volar", - "Vue.vscode-typescript-vue-plugin", "Orta.vscode-jest", "dbaeumer.vscode-eslint", "mrmlnc.vscode-json5" diff --git a/.devcontainer/devcontainer.yml b/.devcontainer/devcontainer.yml index 7ea0929469..beefcfd0a2 100644 --- a/.devcontainer/devcontainer.yml +++ b/.devcontainer/devcontainer.yml @@ -132,6 +132,21 @@ redis: id: 'aidx' +# ┌────────────────┐ +#───┘ Error tracking └────────────────────────────────────────── + +# Sentry is available for error tracking. +# See the Sentry documentation for more details on options. + +#sentryForBackend: +# enableNodeProfiling: true +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + +#sentryForFrontend: +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + # ┌─────────────────────┐ #───┘ Other configuration └───────────────────────────────────── diff --git a/.devcontainer/init.sh b/.devcontainer/init.sh index bcad3e6d85..729e1a9d2d 100755 --- a/.devcontainer/init.sh +++ b/.devcontainer/init.sh @@ -4,6 +4,8 @@ set -xe sudo chown -R node /workspace git submodule update --init +corepack install +corepack enable pnpm config set store-dir /home/node/.local/share/pnpm/store pnpm install --frozen-lockfile cp .devcontainer/devcontainer.yml .config/default.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f725dbf163..84d29851b2 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -11,14 +11,16 @@ testCommit: variables: POSTGRES_PASSWORD: ci script: - - apt-get update && apt-get install -y git wget curl build-essential python3 + - apt-get update && apt-get install -y git wget curl build-essential python3 ffmpeg - cp .config/ci.yml .config/default.yml + - cp .config/ci.yml .config/test.yml - corepack enable - corepack prepare pnpm@latest --activate - git submodule update --init - pnpm install --frozen-lockfile - pnpm run build - pnpm run migrate + - pnpm run --filter='!megalodon' test - pnpm run --filter=backend lint - pnpm run --filter=frontend eslint cache: diff --git a/.node-version b/.node-version index d5a159609d..87834047a6 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -20.10.0 +20.12.2 diff --git a/.old/workflows/lint.yml b/.old/workflows/lint.yml deleted file mode 100644 index 8ad19b45c8..0000000000 --- a/.old/workflows/lint.yml +++ /dev/null @@ -1,95 +0,0 @@ -name: Lint - -on: - push: - branches: - - stable - - develop - paths: - - packages/** - pull_request: - paths: - - packages/backend/** - - packages/frontend/** - - packages/sw/** - - packages/misskey-js/** - - packages/shared/.eslintrc.js - -jobs: - pnpm_install: - runs-on: docker - steps: - - uses: actions/checkout@v4.1.1 - with: - fetch-depth: 0 - submodules: true - - uses: https://github.com/pnpm/action-setup@v2 - with: - version: 8 - run_install: false - - uses: https://code.forgejo.org/actions/setup-node@v4 - with: - node-version-file: '.node-version' - cache: 'pnpm' - - run: corepack enable - - run: pnpm i --frozen-lockfile - - lint: - needs: [pnpm_install] - runs-on: docker - continue-on-error: true - strategy: - matrix: - workspace: - - backend - - frontend - - sw - - misskey-js - steps: - - uses: actions/checkout@v4.1.1 - with: - fetch-depth: 0 - submodules: true - - uses: https://github.com/pnpm/action-setup@v2 - with: - version: 7 - run_install: false - - uses: https://code.forgejo.org/actions/setup-node@v4 - with: - node-version-file: '.node-version' - cache: 'pnpm' - - run: corepack enable - - run: pnpm i --frozen-lockfile - - run: pnpm --filter ${{ matrix.workspace }} run eslint - - typecheck: - needs: [pnpm_install] - runs-on: docker - continue-on-error: true - strategy: - matrix: - workspace: - - backend - - misskey-js - steps: - - uses: actions/checkout@v4.1.1 - with: - fetch-depth: 0 - submodules: true - - uses: https://github.com/pnpm/action-setup@v2 - with: - version: 7 - run_install: false - - uses: https://code.forgejo.org/actions/setup-node@v4 - with: - node-version-file: '.node-version' - cache: 'pnpm' - - run: corepack enable - - run: pnpm i --frozen-lockfile - - run: pnpm --filter misskey-js run build - if: ${{ matrix.workspace == 'backend' }} - - run: pnpm --filter misskey-reversi run build:tsc - if: ${{ matrix.workspace == 'backend' }} - - run: pnpm --filter misskey-bubble-game run build - if: ${{ matrix.workspace == 'backend' }} - - run: pnpm --filter ${{ matrix.workspace }} run typecheck diff --git a/.vscode/extensions.json b/.vscode/extensions.json index baca8db246..3cdf81e339 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -3,9 +3,7 @@ "editorconfig.editorconfig", "dbaeumer.vscode-eslint", "Vue.volar", - "Vue.vscode-typescript-vue-plugin", "Orta.vscode-jest", - "dbaeumer.vscode-eslint", "mrmlnc.vscode-json5" ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index e2a82b1ffe..0ceec23acd 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,7 +7,7 @@ "*.test.ts": "typescript" }, "jest.jestCommandLine": "pnpm run jest", - "jest.autoRun": "off", + "jest.runMode": "on-demand", "editor.codeActionsOnSave": { "source.fixAll": "explicit" }, diff --git a/CHANGELOG.md b/CHANGELOG.md index bafee277d2..f93811c606 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,119 @@ - +### Server +- チャート生成時にinstance.suspentionStateに置き換えられたinstance.isSuspendedが参照されてしまう問題を修正 + + +## 2024.5.0 + +### Note +- コントロールパネル内にあるサマリープロキシの設定個所がセキュリティから全般へ変更となります。 +- 悪意のある第三者がリモートユーザーになりすましたアクティビティを受け取れてしまう問題を修正しました。詳しくは[GitHub security advisory](https://github.com/misskey-dev/misskey/security/advisories/GHSA-2vxv-pv3m-3wvj)をご覧ください。 +- 管理者向け権限 `read:admin:show-users` は `read:admin:show-user` に統合されました。必要に応じてAPIトークンを再発行してください。 + +### General +- Feat: エラートラッキングにSentryを使用できるようになりました +- Enhance: URLプレビューの有効化・無効化を設定できるように #13569 +- Enhance: アンテナでBotによるノートを除外できるように + (Cherry-picked from https://github.com/MisskeyIO/misskey/pull/545) +- Enhance: クリップのノート数を表示するように +- Enhance: コンディショナルロールの条件として以下を新たに追加 (#13667) + - 猫ユーザーか + - botユーザーか + - サスペンド済みユーザーか + - 鍵アカウントユーザーか + - 「アカウントを見つけやすくする」が有効なユーザーか +- Enhance: Goneを出さずに終了したサーバーへの配信停止を自動的に行うように + - もしそのようなサーバーからから配信が届いた場合には自動的に配信を再開します +- Enhance: 配信停止の理由を表示するように +- Enhance: サーバーのお問い合わせ先URLを設定できるようになりました +- Fix: Play作成時に設定した公開範囲が機能していない問題を修正 +- Fix: 正規化されていない状態のhashtagが連合されてきたhtmlに含まれているとhashtagが正しくhashtagに復元されない問題を修正 +- Fix: みつけるのアンケート欄にてチャンネルのアンケートが含まれてしまう問題を修正 + +### Client +- Feat: アップロードするファイルの名前をランダム文字列にできるように +- Feat: 個別のお知らせにリンクで飛べるように + (Based on https://github.com/MisskeyIO/misskey/pull/639) +- Enhance: 自分のノートの添付ファイルから直接ファイルの詳細ページに飛べるように +- Enhance: 広告がMisskeyと同一ドメインの場合はRouterで遷移するように +- Enhance: リアクション・いいねの総数を表示するように +- Enhance: リアクション受け入れが「いいねのみ」の場合はリアクション絵文字一覧を表示しないように +- Enhance: 設定>プラグインのページからプラグインの簡易的なログやエラーを見られるように + - 実装の都合により、プラグインは1つエラーを起こした時に即時停止するようになりました +- Enhance: ページのデザインを変更 +- Enhance: 2要素認証(ワンタイムパスワード)の入力欄を改善 +- Enhance: 「今日誕生日のフォロー中ユーザー」ウィジェットを手動でリロードできるように +- Enhance: 映像・音声の再生にブラウザのネイティブプレイヤーを使用できるように +- Enhance: 映像・音声の再生メニューに「再生速度」「ループ再生」「ピクチャインピクチャ」を追加 +- Enhance: 映像・音声の再生にキーボードショートカットが使えるように +- Enhance: ノートについているリアクションの「もっと!」から、リアクションの一覧を表示できるように +- Enhance: リプライにて引用がある場合テキストが空でもノートできるように + - 引用したいノートのURLをコピーしリプライ投稿画面にペーストして添付することで達成できます +- Enhance: フォローするかどうかの確認ダイアログを出せるように +- Enhance: Playを手動でリロードできるように +- Enhance: 通報のコメント内のリンクをクリックした際、ウィンドウで開くように +- Enhance: `Ui:C:postForm` および `Ui:C:postFormButton` に `localOnly` と `visibility` を設定できるように +- Enhance: AiScriptを0.18.0にバージョンアップ +- Enhance: 通常のノートでも、お気に入りに登録したチャンネルにリノートできるように +- Enhance: 長いテキストをペーストした際にテキストファイルとして添付するかどうかを選択できるように +- Enhance: 新着ノートをサウンドで通知する機能をdeck UIに追加しました +- Enhance: コントロールパネルのクイックアクションからファイルを照会できるように +- Enhance: コントロールパネルのクイックアクションから通常の照会を行えるように +- Fix: 一部のページ内リンクが正しく動作しない問題を修正 +- Fix: 周年の実績が閏年を考慮しない問題を修正 +- Fix: ローカルURLのプレビューポップアップが左上に表示される +- Fix: WebGL2をサポートしないブラウザで「季節に応じた画面の演出」が有効になっているとき、Misskeyが起動できなくなる問題を修正 + (Cherry-picked from https://activitypub.software/TransFem-org/Sharkey/-/merge_requests/459) +- Fix: ページタイトルでローカルユーザーとリモートユーザーの区別がつかない問題を修正 + (Cherry-picked from https://github.com/MisskeyIO/misskey/pull/528) +- Fix: コードブロックのシンタックスハイライトで使用される定義ファイルをCDNから取得するように #13177 + - CDNから取得せずMisskey本体にバンドルする場合は`pacakges/frontend/vite.config.ts`を修正してください。 +- Fix: タイムゾーンによっては、「今日誕生日のフォロー中ユーザー」ウィジェットが正しく動作しない問題を修正 +- Fix: CWのみの引用リノートが詳細ページで純粋なリノートとして誤って扱われてしまう問題を修正 +- Fix: ノート詳細ページにおいてCW付き引用リノートのCWボタンのラベルに「引用」が含まれていない問題を修正 +- Fix: ダイアログの入力で字数制限に違反していてもEnterキーが押せてしまう問題を修正 +- Fix: ダイレクト投稿の宛先が保存されない問題を修正 +- Fix: Playのページを離れたときに、Playが正常に初期化されない問題を修正 +- Fix: ページのOGP URLが間違っているのを修正 +- Fix: リバーシの対局を正しく共有できないことがある問題を修正 +- Fix: 通知をグループ化している際に、人数が正常に表示されないことがある問題を修正 +- Fix: 連合なしの状態の読み書きができない問題を修正 +- Fix: `/share` で日本語等を含むurlがurlエンコードされない問題を修正 +- Fix: ファイルを5つ以上添付してもテキストがないとノートが折りたたまれない問題を修正 + +### Server +- Enhance: エンドポイント`antennas/update`の必須項目を`antennaId`のみに +- Enhance: misskey-dev/summaly@5.1.0の取り込み(プレビュー生成処理の効率化) +- Enhance: ドライブのファイルがNSFWかどうか個別に連合されるように (#13756) + - 可能な場合、ノートの添付ファイルのセンシティブ判定がファイル単位になります +- Fix: リモートから配送されたアクティビティにJSON-LD compactionをかける +- Fix: フォローリクエストを作成する際に既存のものは削除するように + (Cherry-picked from https://activitypub.software/TransFem-org/Sharkey/-/merge_requests/440) +- Fix: エンドポイント`notes/translate`のエラーを改善 +- Fix: CleanRemoteFilesProcessorService report progress from 100% (#13632) +- Fix: 一部の音声ファイルが映像ファイルとして扱われる問題を修正 +- Fix: リプライのみの引用リノートと、CWのみの引用リノートが純粋なリノートとして誤って扱われてしまう問題を修正 +- Fix: 登録にメール認証が必須になっている場合、登録されているメールアドレスを削除できないように + (Cherry-picked from https://github.com/MisskeyIO/misskey/pull/606) +- Fix: Add Cache-Control to Bull Board +- Fix: nginx経由で/files/にRangeリクエストされた場合に正しく応答できないのを修正 +- Fix: 一部のタイムラインのストリーミングでインスタンスミュートが効かない問題を修正 +- Fix: グローバルタイムラインで返信が表示されないことがある問題を修正 +- Fix: リノートをミュートしたユーザの投稿のリノートがミュートされる問題を修正 +- Fix: AP Link等は添付ファイル扱いしないようになど (#13754) +- Fix: FTTが有効かつsinceIdのみを指定した場合に帰って来るレスポンスが逆順である問題を修正 +- Fix: `/i/notifications`に `includeTypes`か`excludeTypes`を指定しているとき、通知が存在するのに空配列を返すことがある問題を修正 +- Fix: 複数idを指定する`users/show`が関係ないユーザを返すことがある問題を修正 +- Fix: `/tags` と `/user-tags` が検索エンジンにインデックスされないように +- Fix: もともとセンシティブではないと連合されていたファイルがセンシティブとして連合された場合にセンシティブとしてそのファイルを扱うように + - センシティブとして連合したファイルは非センシティブとして連合されてもセンシティブとして扱われます ## 2024.3.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 50f323fab0..2acacd6dfa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -307,6 +307,98 @@ export const handlers = [ Don't forget to re-run the `.storybook/generate.js` script after adding, editing, or removing the above files. +## Nest + +### Nest Service Circular dependency / Nestでサービスの循環参照でエラーが起きた場合 + +#### forwardRef +まずは簡単に`forwardRef`を試してみる + +```typescript +export class FooService { + constructor( + @Inject(forwardRef(() => BarService)) + private barService: BarService + ) { + } +} +``` + +#### OnModuleInit +できなければ`OnModuleInit`を使う + +```typescript +import { Injectable, OnModuleInit } from '@nestjs/common'; +import { ModuleRef } from '@nestjs/core'; +import { BarService } from '@/core/BarService'; + +@Injectable() +export class FooService implements OnModuleInit { + private barService: BarService // constructorから移動してくる + + constructor( + private moduleRef: ModuleRef, + ) { + } + + async onModuleInit() { + this.barService = this.moduleRef.get(BarService.name); + } + + public async niceMethod() { + return await this.barService.incredibleMethod({ hoge: 'fuga' }); + } +} +``` + +##### Service Unit Test +テストで`onModuleInit`を呼び出す必要がある + +```typescript +// import ... + +describe('test', () => { + let app: TestingModule; + let fooService: FooService; // for test case + let barService: BarService; // for test case + + beforeEach(async () => { + app = await Test.createTestingModule({ + imports: ..., + providers: [ + FooService, + { // mockする (mockは必須ではないかもしれない) + provide: BarService, + useFactory: () => ({ + incredibleMethod: jest.fn(), + }), + }, + { // Provideにする + provide: BarService.name, + useExisting: BarService, + }, + ], + }) + .useMocker(... + .compile(); + + fooService = app.get(FooService); + barService = app.get(BarService) as jest.Mocked; + + // onModuleInitを実行する + await fooService.onModuleInit(); + }); + + test('nice', () => { + await fooService.niceMethod(); + + expect(barService.incredibleMethod).toHaveBeenCalled(); + expect(barService.incredibleMethod.mock.lastCall![0]) + .toEqual({ hoge: 'fuga' }); + }); +}) +``` + ## Notes ### Misskeyのドメイン固有の概念は`Mi`をprefixする @@ -457,7 +549,9 @@ https://github.com/misskey-dev/misskey.git`), then: git checkout -m merge/$(date +%Y-%m-%d) # or whatever git merge --no-ff misskey/develop -fix conflicts and *commit*! +fix conflicts and *commit*! (conflicts in `pnpm-lock.yaml` can usually +be fixed by running `pnpm install`, it detects conflict markers and +seems to do a decent job) *after that commit*, do all the extra work, on the same branch: @@ -468,7 +562,23 @@ fix conflicts and *commit*! * from `ApNoteService.createNote` to `ApNoteService.updateNote` * from `endoints/notes/create.ts` to `endoints/notes/edit.ts` * from `MkNote*` to `SkNote*` (if sensible) + * from the global timeline to the bubble timeline + (`packages/backend/src/server/api/stream/channels/global-timeline.ts`, + `packages/backend/src/server/api/stream/channels/bubble-timeline.ts`, + `packages/frontend/src/components/MkTimeline.vue`, + `packages/frontend/src/pages/timeline.vue`, + `packages/frontend/src/ui/deck/tl-column.vue`, + `packages/frontend/src/widgets/WidgetTimeline.vue`) +* make sure there aren't any new `ti-*` classes (Tabler Icons), and + replace them with appropriate `ph-*` ones (Phosphor Icons). + `git grep '["'\'']ti[ -](?!fw)'` should show you what to change. + NOTE: `ti-fw` is a special class that's defined by Misskey, leave it + alone +* re-generate `misskey-js`: `pnpm build-misskey-js-with-types` * run tests `pnpm test` and fix as much as you can + * right now `megalodon` doesn't pass its tests, you probably need to + run `pnpm --filter=backend test` (requires a test database, [see + above](#testing)) and `pnpm --filter=frontend test` * run lint `pnpm --filter=backend lint` + `pnpm --filter=frontend eslint` and fix as much as you can diff --git a/Dockerfile b/Dockerfile index 7e0a778862..b937c69cdb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # syntax = docker/dockerfile:1.4 -ARG NODE_VERSION=20.10.0-alpine3.18 +ARG NODE_VERSION=20.12.2-alpine3.19 FROM node:${NODE_VERSION} as build @@ -8,8 +8,7 @@ RUN apk add git linux-headers build-base ENV PYTHONUNBUFFERED=1 RUN apk add --update python3 && ln -sf python3 /usr/bin/python -RUN python3 -m ensurepip -RUN pip3 install --no-cache --upgrade pip setuptools +RUN apk add py3-pip py3-setuptools RUN corepack enable @@ -65,7 +64,7 @@ COPY --chown=sharkey:sharkey --from=build /sharkey/sharkey-assets ./packages/fro COPY --chown=sharkey:sharkey package.json ./package.json COPY --chown=sharkey:sharkey pnpm-workspace.yaml ./pnpm-workspace.yaml COPY --chown=sharkey:sharkey packages/backend/package.json ./packages/backend/package.json -COPY --chown=sharkey:sharkey packages/backend/check_connect.js ./packages/backend/check_connect.js +COPY --chown=sharkey:sharkey packages/backend/scripts/check_connect.js ./packages/backend/scripts/check_connect.js COPY --chown=sharkey:sharkey packages/backend/ormconfig.js ./packages/backend/ormconfig.js COPY --chown=sharkey:sharkey packages/backend/migration ./packages/backend/migration COPY --chown=sharkey:sharkey packages/backend/assets ./packages/backend/assets diff --git a/chart/files/default.yml b/chart/files/default.yml index 9c81964736..2e1381ec57 100644 --- a/chart/files/default.yml +++ b/chart/files/default.yml @@ -152,6 +152,22 @@ redis: # ID SETTINGS AFTER THAT! id: "aidx" + +# ┌────────────────┐ +#───┘ Error tracking └────────────────────────────────────────── + +# Sentry is available for error tracking. +# See the Sentry documentation for more details on options. + +#sentryForBackend: +# enableNodeProfiling: true +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + +#sentryForFrontend: +# options: +# dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0' + # ┌─────────────────────┐ #───┘ Other configuration └───────────────────────────────────── diff --git a/cypress/e2e/basic.cy.js b/cypress/e2e/basic.cy.ts similarity index 98% rename from cypress/e2e/basic.cy.js rename to cypress/e2e/basic.cy.ts index 604241d13c..d2525e0a7d 100644 --- a/cypress/e2e/basic.cy.js +++ b/cypress/e2e/basic.cy.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + describe('Before setup instance', () => { beforeEach(() => { cy.resetState(); diff --git a/cypress/e2e/router.cy.js b/cypress/e2e/router.cy.ts similarity index 91% rename from cypress/e2e/router.cy.js rename to cypress/e2e/router.cy.ts index 6de27be5f4..8d8fb3af31 100644 --- a/cypress/e2e/router.cy.js +++ b/cypress/e2e/router.cy.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + describe('Router transition', () => { describe('Redirect', () => { // サーバの初期化。ルートのテストに関しては各describeごとに1度だけ実行で十分だと思う(使いまわした方が早い) diff --git a/cypress/e2e/widgets.cy.js b/cypress/e2e/widgets.cy.ts similarity index 95% rename from cypress/e2e/widgets.cy.js rename to cypress/e2e/widgets.cy.ts index df6ec8357d..847801a69f 100644 --- a/cypress/e2e/widgets.cy.js +++ b/cypress/e2e/widgets.cy.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + /* flaky describe('After user signed in', () => { beforeEach(() => { diff --git a/cypress/support/commands.js b/cypress/support/commands.ts similarity index 87% rename from cypress/support/commands.js rename to cypress/support/commands.ts index 91a4d7abe6..281f2e6ccd 100644 --- a/cypress/support/commands.js +++ b/cypress/support/commands.ts @@ -30,9 +30,13 @@ Cypress.Commands.add('visitHome', () => { }) Cypress.Commands.add('resetState', () => { - cy.window(win => { + // iframe.contentWindow.indexedDB.deleteDatabase() がchromeのバグで使用できないため、indexedDBを無効化している。 + // see https://github.com/misskey-dev/misskey/issues/13605#issuecomment-2053652123 + /* + cy.window().then(win => { win.indexedDB.deleteDatabase('keyval-store'); }); + */ cy.request('POST', '/api/reset-db', {}).as('reset'); cy.get('@reset').its('status').should('equal', 204); cy.reload(true); diff --git a/cypress/support/e2e.js b/cypress/support/e2e.ts similarity index 100% rename from cypress/support/e2e.js rename to cypress/support/e2e.ts diff --git a/cypress/support/index.ts b/cypress/support/index.ts new file mode 100644 index 0000000000..c1bed21979 --- /dev/null +++ b/cypress/support/index.ts @@ -0,0 +1,19 @@ +declare global { + namespace Cypress { + interface Chainable { + login(username: string, password: string): Chainable; + + registerUser( + username: string, + password: string, + isAdmin?: boolean + ): Chainable; + + resetState(): Chainable; + + visitHome(): Chainable; + } + } +} + +export {} diff --git a/cypress/tsconfig.json b/cypress/tsconfig.json new file mode 100644 index 0000000000..6fe7f32cc4 --- /dev/null +++ b/cypress/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "lib": ["dom", "es5"], + "target": "es5", + "types": ["cypress", "node"] + }, + "include": ["./**/*.ts"] +} diff --git a/healthcheck.sh b/healthcheck.sh index 02f13576e9..216776b28f 100644 --- a/healthcheck.sh +++ b/healthcheck.sh @@ -4,4 +4,4 @@ # SPDX-License-Identifier: AGPL-3.0-only PORT=$(grep '^port:' /sharkey/.config/default.yml | awk 'NR==1{print $2; exit}') -curl -s -S -o /dev/null "http://localhost:${PORT}" +curl -Sfso/dev/null "http://localhost:${PORT}/healthz" diff --git a/locales/ar-SA.yml b/locales/ar-SA.yml index 17c8f24fa5..955d672c1d 100644 --- a/locales/ar-SA.yml +++ b/locales/ar-SA.yml @@ -123,6 +123,7 @@ reactions: "التفاعلات" reactionSettingDescription2: "اسحب لترتيب ، انقر للحذف ، استخدم \"+\" للإضافة." rememberNoteVisibility: "تذكر إعدادت مدى رؤية الملاحظات" attachCancel: "أزل المرفق" +deleteFile: "حُذف الملف" markAsSensitive: "علّمه كمحتوى حساس" unmarkAsSensitive: "ألغ تعيينه كمحتوى حساس" enterFileName: "ادخل اسم الملف" @@ -1015,6 +1016,8 @@ sourceCode: "الشفرة المصدرية" flip: "اقلب" lastNDays: "آخر {n} أيام" surrender: "ألغِ" +_delivery: + stop: "مُعلّق" _initialAccountSetting: accountCreated: "نجح إنشاء حسابك!" letsStartAccountSetup: "إذا كنت جديدًا لنعدّ حسابك الشخصي." @@ -1565,8 +1568,21 @@ _webhookSettings: reaction: "عند التفاعل" _moderationLogTypes: suspend: "علِق" + deleteDriveFile: "حُذف الملف" + deleteNote: "حُذفت الملاحظة" + createGlobalAnnouncement: "أُنشئ إعلان عام" + createUserAnnouncement: "أُنشئ إعلان مستخدم" + updateGlobalAnnouncement: "حُدث إعلان عام" + updateUserAnnouncement: "حُدث إعلان مستخدم" resetPassword: "أعد تعيين كلمتك السرية" createInvitation: "ولِّد دعوة" _reversi: total: "المجموع" - + lookingForPlayer: "يبحث عن خصم..." + gameCanceled: "أُلغيت اللعبة." + opponentHasSettingsChanged: "غيَر الخصم إعدادته." + showBoardLabels: "اعرض ترقيم الصفوف والأعمدة على اللوح" + useAvatarAsStone: "حوَل الحجارة إلى صور مستخدمين" +_offlineScreen: + title: "غير متصل - يتعذر الاتصال بالخادم" + header: "يتعذر الاتصال بالخادم" diff --git a/locales/bn-BD.yml b/locales/bn-BD.yml index 2a23cda06b..abcf07da83 100644 --- a/locales/bn-BD.yml +++ b/locales/bn-BD.yml @@ -857,6 +857,10 @@ replies: "জবাব" renotes: "রিনোট" sourceCode: "সোর্স কোড" flip: "উল্টান" +_delivery: + stop: "স্থগিত করা হয়েছে" + _type: + none: "প্রকাশ করা হচ্ছে" _role: priority: "অগ্রাধিকার" _priority: @@ -1347,4 +1351,3 @@ _moderationLogTypes: resetPassword: "পাসওয়ার্ড রিসেট করুন" _reversi: total: "মোট" - diff --git a/locales/ca-ES.yml b/locales/ca-ES.yml index 985f658999..bda8579e27 100644 --- a/locales/ca-ES.yml +++ b/locales/ca-ES.yml @@ -400,6 +400,7 @@ name: "Nom" antennaSource: "Font de l'antena" antennaKeywords: "Paraules clau a seguir" antennaExcludeKeywords: "Paraules clau a excloure" +antennaExcludeBots: "Exclou els bots" antennaKeywordsDescription: "Separar amb espais per la condició AND o amb salts de línia per la condició OR." notifyAntenna: "Notifica'm les publicacions noves" withFileAntenna: "Només les publicacions amb fitxers" @@ -494,6 +495,7 @@ emojiStyle: "Estil d'emoji" native: "Nadiu" disableDrawer: "No mostrar els menús en calaixos" showNoteActionsOnlyHover: "Només mostra accions de la nota en passar amb el cursor" +showReactionsCount: "Mostra el nombre de reaccions a les publicacions" noHistory: "No hi ha un registre previ" signinHistory: "Historial d'autenticacions" enableAdvancedMfm: "Habilitar l'MFM avançat" @@ -543,7 +545,7 @@ objectStorageUseProxyDesc: "Desactiva'l si no faràs servir un Proxy per les con objectStorageSetPublicRead: "Configurar les pujades com públiques " s3ForcePathStyleDesc: "Si s3ForcePathStyle es troba activat el nom del dipòsit s'ha d'incloure a l'adreça URL en comtes del nom del host. Potser que necessitis activar-ho quan facis servir, per exemple, Minio a un servidor propi." serverLogs: "Registres del servidor" -deleteAll: "Esborrar tot" +deleteAll: "Elimina-ho tot" showFixedPostForm: "Mostrar el formulari per escriure a l'inici de la línia de temps" showFixedPostFormInChannel: "Mostrar el formulari d'escriptura al principi de la línia de temps (Canals)" withRepliesByDefaultForNewlyFollowed: "Inclou les respostes d'usuaris nous seguits a la línia de temps per defecte." @@ -691,9 +693,9 @@ reporter: "Denunciant " reporteeOrigin: "Origen de la denúncia " reporterOrigin: "Origen del denunciant" forwardReport: "Transferir la denúncia a una instància remota" -forwardReportIsAnonymous: "En comptes del teu compte, es farà servir un compte anònim com a denunciat a la instància remota." -send: "Enviar" -abuseMarkAsResolved: "Marcar la denúncia com a resolta" +forwardReportIsAnonymous: "En lloc del teu compte, es farà servir un compte anònim com a denunciant al servidor remot." +send: "Envia" +abuseMarkAsResolved: "Marca la denúncia com a resolta" openInNewTab: "Obre a una pestanya nova" openInSideView: "Obre a una vista lateral" defaultNavigationBehaviour: "Navegació per defecte" @@ -853,7 +855,7 @@ customCss: "CSS personalitzat" customCssWarn: "Aquesta configuració només hauries de configurar-la si saps que fas. Si poses valors inadequats pots fer que el client deixi de funcionar correctament." global: "Global" squareAvatars: "Mostrar avatars quadrats" -sent: "Enviar" +sent: "Envia" received: "Rebut" searchResult: "Resultats de la cerca" hashtags: "Etiquetes" @@ -991,6 +993,7 @@ neverShow: "No mostrar més " remindMeLater: "Recorda-m'ho més tard" didYouLikeMisskey: "T'està agradant Misskey?" pleaseDonate: "A {host} fem servir el software lliure Misskey. Considera fer un donatiu a Misskey perquè pugui continuar el seu desenvolupament!" +correspondingSourceIsAvailable: "El codi font corresponent està disponible a {anchor}." roles: "Rols" role: "Rols" noRole: "No s'han trobat rols" @@ -1159,6 +1162,7 @@ showRenotes: "Mostrar impulsos" edited: "Editat" notificationRecieveConfig: "Paràmetres de notificacions" mutualFollow: "Seguidor mutu" +followingOrFollower: "Seguit o seguidor" fileAttachedOnly: "Només notes amb adjunts" showRepliesToOthersInTimeline: "Mostrar les respostes a altres a la línia de temps" hideRepliesToOthersInTimeline: "Amagar les respostes a altres a la línia de temps" @@ -1168,6 +1172,9 @@ confirmShowRepliesAll: "Aquesta opció no té marxa enrere. Vols mostrar les tev confirmHideRepliesAll: "Aquesta opció no té marxa enrere. Vols ocultar les teves respostes a tots els usuaris que segueixes a la línia de temps?" externalServices: "Serveis externs" sourceCode: "Codi font" +repositoryUrl: "URL del repositori" +feedback: "Opinió" +feedbackUrl: "URL per a opinar" impressum: "Impressum" impressumUrl: "Adreça URL impressum" impressumDescription: "A països, com Alemanya, la inclusió de la informació de contacte de l'operador (un Impressum) és requereix de manera legal per llocs comercials." @@ -1203,6 +1210,7 @@ soundWillBePlayed: "Es reproduiran efectes de so" showReplay: "Veure reproducció" replay: "Reproduir" replaying: "Reproduint" +endReplay: "Tanca la redifusió" ranking: "Classificació" lastNDays: "Últims {n} dies" backToTitle: "Torna al títol" @@ -1210,7 +1218,16 @@ hemisphere: "Geolocalització" withSensitive: "Incloure notes amb fitxers sensibles" userSaysSomethingSensitive: "La publicació de {name} conte material sensible" enableHorizontalSwipe: "Lliscar per canviar de pestanya" +loading: "S’està carregant" surrender: "Cancel·lar " +gameRetry: "Torna a provar" +notUsePleaseLeaveBlank: "Si no voleu usar-ho, deixeu-ho en blanc" +useTotp: "Usa una contrasenya d'un sol ús" +useBackupCode: "Usa un codi de recuperació" +_delivery: + stop: "Suspés" + _type: + none: "S'està publicant" _bubbleGame: howToPlay: "Com es juga" _howToPlay: @@ -1915,7 +1932,6 @@ _2fa: registerTOTP: "Registrar una aplicació autenticadora" step1: "Primer instal·la una aplicació autenticadora (com {a} o {b}) al teu dispositiu." step2: "Després escaneja el codi QR que es mostra en aquesta pantalla." - step2Click: "Fent clic en aquest codi QR et permetrà registrar l'autenticació de doble factor a la teva clau de seguretat o en l'aplicació d'autenticació del teu dispositiu." step2Uri: "Escriu la següent URI si estàs fent servir una aplicació d'escriptori " step3Title: "Escriu un codi d'autenticació" step3: "Escriu el codi d'autenticació (token) que es mostra a la teva aplicació per finalitzar la configuració." @@ -1989,7 +2005,6 @@ _permissions: "read:admin:server-info": "Veure informació del servidor" "read:admin:show-moderation-log": "Veure registre de moderació " "read:admin:show-user": "Veure informació privada de l'usuari " - "read:admin:show-users": "Veure informació privada de l'usuari " "write:admin:suspend-user": "Suspendre usuari" "write:admin:unset-user-avatar": "Esborrar avatar d'usuari " "write:admin:unset-user-banner": "Esborrar bàner de l'usuari " diff --git a/locales/cs-CZ.yml b/locales/cs-CZ.yml index 6dad336b7f..bcab28db2c 100644 --- a/locales/cs-CZ.yml +++ b/locales/cs-CZ.yml @@ -1099,6 +1099,10 @@ sourceCode: "Zdrojový kód" flip: "Otočit" lastNDays: "Posledních {n} dnů" surrender: "Zrušit" +_delivery: + stop: "Suspendováno" + _type: + none: "Publikuji" _initialAccountSetting: accountCreated: "Váš účet byl úspěšně vytvořen!" letsStartAccountSetup: "Pro začátek si nastavte svůj profil." @@ -1664,7 +1668,6 @@ _2fa: registerTOTP: "Registrovat aplikaci autentizátoru" step1: "Nejprve si do zařízení nainstalujte aplikaci pro ověřování (například {a} nebo {b})." step2: "Poté naskenujte QR kód zobrazený na této obrazovce." - step2Click: "Kliknutím na tento QR kód můžete zaregistrovat 2FA do bezpečnostního klíče nebo aplikace autentizace telefonu." step3Title: "Zadejte ověřovací kód" step3: "Pro dokončení nastavení zadejte token poskytnutý vaší aplikací." step4: "Od této chvíle budou všechny budoucí pokusy o přihlášení vyžadovat tento přihlašovací token." @@ -1718,7 +1721,7 @@ _auth: shareAccessTitle: "Udělovat oprávnění k aplikacím" shareAccess: "Chcete autorizovat \"{name}\" pro přístup k tomuto účtu?" shareAccessAsk: "Opravdu chcete této aplikaci povolit přístup k vašemu účtu?" - permission: "{jméno} požaduje tato oprávnění" + permission: "{name} požaduje tato oprávnění" permissionAsk: "Tato aplikace požaduje následující oprávnění" pleaseGoBack: "Vraťte se prosím zpět do aplikace" callback: "Návrat k aplikaci" @@ -1942,7 +1945,7 @@ _notification: youGotMention: "{name} vás zmínil" youGotReply: "{name} vám odpověděl" youGotQuote: "{name} vás citoval" - youRenoted: "Poznámka od {jméno}" + youRenoted: "Poznámka od {name}" youWereFollowed: "Máte nového následovníka" youReceivedFollowRequest: "Obdrželi jste žádost o sledování" yourFollowRequestAccepted: "Vaše žádost o sledování byla přijata" @@ -2025,4 +2028,3 @@ _moderationLogTypes: createInvitation: "Vygenerovat pozvánku" _reversi: total: "Celkem" - diff --git a/locales/da-DK.yml b/locales/da-DK.yml index d1fbec9f67..5eb7a5a5f4 100644 --- a/locales/da-DK.yml +++ b/locales/da-DK.yml @@ -1,3 +1,4 @@ --- _lang_: "Dansk" - +headlineMisskey: "" +introMisskey: "ようこそ!Misskeyは、オープンソースの分散型マイクロブログサービスです。\n「ノート」を作成して、いま起こっていることを共有したり、あなたについて皆に発信しよう📡\n「リアクション」機能で、皆のノートに素早く反応を追加することもできます👍\n新しい世界を探検しよう🚀" diff --git a/locales/de-DE.yml b/locales/de-DE.yml index 7cb451e233..47b97a8e82 100644 --- a/locales/de-DE.yml +++ b/locales/de-DE.yml @@ -654,7 +654,7 @@ smtpSecureInfo: "Schalte dies aus, falls du STARTTLS verwendest." testEmail: "Emailversand testen" wordMute: "Wortstummschaltung" regexpError: "Fehler in einem regulären Ausdruck" -regexpErrorDescription: "Im regulären Ausdruck deiner {tab}en Wortstummschaltungen ist ein Fehler aufgetreten:" +regexpErrorDescription: "Im regulären Ausdruck deiner in Zeile {line} von {tab}en Wortstummschaltungen ist ein Fehler aufgetreten:" instanceMute: "Instanzstummschaltungen" userSaysSomething: "{name} hat etwas gesagt" makeActive: "Aktivieren" @@ -1188,6 +1188,10 @@ addMfmFunction: "MFM hinzufügen" sfx: "Soundeffekte" lastNDays: "Letzten {n} Tage" surrender: "Abbrechen" +_delivery: + stop: "Gesperrt" + _type: + none: "Wird veröffentlicht" _announcement: forExistingUsers: "Nur für existierende Nutzer" forExistingUsersDescription: "Ist diese Option aktiviert, wird diese Ankündigung nur Nutzern angezeigt, die zum Zeitpunkt der Ankündigung bereits registriert sind. Ist sie deaktiviert, wird sie auch Nutzern, die sich nach dessen Veröffentlichung registrieren, angezeigt." @@ -1822,7 +1826,6 @@ _2fa: registerTOTP: "Authentifizierungs-App registrieren" step1: "Installiere zuerst eine Authentifizierungsapp (z.B. {a} oder {b}) auf deinem Gerät." step2: "Dann, scanne den angezeigten QR-Code mit deinem Gerät." - step2Click: "Durch Klicken dieses QR-Codes kannst du Verifikation mit deinem Security-Token oder einer App registrieren." step2Uri: "Nutzt du ein Desktopprogramm, gib folgende URI eingeben" step3Title: "Authentifizierungsscode eingeben" step3: "Gib zum Abschluss den Code (Token) ein, der von deiner App angezeigt wird." @@ -2292,4 +2295,3 @@ _reversi: black: "Schwarz" white: "Weiß" total: "Gesamt" - diff --git a/locales/el-GR.yml b/locales/el-GR.yml index bb5639a741..2098c7ef50 100644 --- a/locales/el-GR.yml +++ b/locales/el-GR.yml @@ -398,4 +398,3 @@ _moderationLogTypes: suspend: "Αποβολή" _reversi: total: "Σύνολο" - diff --git a/locales/en-US.yml b/locales/en-US.yml index 124ebcec60..22d30a871c 100644 --- a/locales/en-US.yml +++ b/locales/en-US.yml @@ -112,11 +112,14 @@ unrenote: "Remove boost" renoted: "Boosted." quoted: "Quoted." rmboost: "Unboosted." +renotedToX: "Boosted to {name}" cantRenote: "This post can't be boosted." cantReRenote: "A boost can't be boosted." quote: "Quote" inChannelRenote: "Channel-only Boost" inChannelQuote: "Channel-only Quote" +renoteToChannel: "Renote to channel" +renoteToOtherChannel: "Renote to other channel" pinnedNote: "Pinned note" pinned: "Pin to profile" you: "You" @@ -323,6 +326,7 @@ selectFile: "Select a file" selectFiles: "Select files" selectFolder: "Select a folder" selectFolders: "Select folders" +fileNotSelected: "No file selected" renameFile: "Rename file" folderName: "Folder name" createFolder: "Create a folder" @@ -411,6 +415,7 @@ name: "Name" antennaSource: "Antenna source" antennaKeywords: "Keywords to listen to" antennaExcludeKeywords: "Keywords to exclude" +antennaExcludeBots: "Exclude bot accounts" antennaKeywordsDescription: "Separate with spaces for an AND condition or with line breaks for an OR condition." notifyAntenna: "Notify about new notes" withFileAntenna: "Only notes with files" @@ -480,6 +485,7 @@ expandAllCws: "Show content for all replies" collapseAllCws: "Hide content for all replies" quoteAttached: "Quote" quoteQuestion: "Append as quote?" +attachAsFileQuestion: "The text in clipboard is long. Would you like to attach it as a text file?" noMessagesYet: "No messages yet" newMessageExists: "There are new messages" onlyOneFileCanBeAttached: "You can only attach one file to a message" @@ -507,6 +513,7 @@ emojiStyle: "Emoji style" native: "Native" disableDrawer: "Don't use drawer-style menus" showNoteActionsOnlyHover: "Only show note actions on hover" +showReactionsCount: "Show the number of reactions in notes" noHistory: "No history available" signinHistory: "Login history" enableAdvancedMfm: "Enable advanced MFM" @@ -854,6 +861,7 @@ administration: "Management" accounts: "Accounts" switch: "Switch" noMaintainerInformationWarning: "Maintainer information is not configured." +noInquiryUrlWarning: "Contact URL is not set." noBotProtectionWarning: "Bot protection is not configured." configure: "Configure" postToGallery: "Create new gallery post" @@ -1062,6 +1070,7 @@ thisPostIsMissingAltTextCancel: "Cancel" thisPostIsMissingAltTextIgnore: "Post anyway" thisPostIsMissingAltText: "One of the files attached to this post is missing alt text. Please ensure all the attachments have alt text." collapseRenotes: "Collapse boosts you've already seen" +collapseRenotesDescription: "Collapse boosts that you have boosted or reacted to" collapseNotesRepliedTo: "Collapse notes replied to" collapseFiles: "Collapse files" autoloadConversation: "Load conversation on replies" @@ -1279,6 +1288,25 @@ enableHorizontalSwipe: "Swipe to switch tabs" loading: "Loading" surrender: "Cancel" gameRetry: "Retry" +notUsePleaseLeaveBlank: "Leave blank if not used" +useTotp: "Enter the One-Time Password" +useBackupCode: "Use the backup codes" +launchApp: "Launch the app" +useNativeUIForVideoAudioPlayer: "Use UI of browser when play video and audio" +keepOriginalFilename: "Keep original file name" +keepOriginalFilenameDescription: "If you turn off this setting, files names will be replaced with random string automatically when you upload files." +noDescription: "No description" +alwaysConfirmFollow: "Always confirm when following" +inquiry: "Contact" +_delivery: + status: "Delivery status" + stop: "Suspended" + resume: "Delivery resume" + _type: + none: "Publishing" + manuallySuspended: "Manually suspended" + goneSuspended: "Server is suspended due to server deletion" + autoSuspendedForNotResponding: "Server is suspended due to no responding" _bubbleGame: howToPlay: "How to play" hold: "Hold" @@ -1404,6 +1432,8 @@ _serverSettings: fanoutTimelineDescription: "Greatly increases performance of timeline retrieval and reduces load on the database when enabled. In exchange, memory usage of Redis will increase. Consider disabling this in case of low server memory or server instability." fanoutTimelineDbFallback: "Fallback to database" fanoutTimelineDbFallbackDescription: "When enabled, the timeline will fall back to the database for additional queries if the timeline is not cached. Disabling it further reduces the server load by eliminating the fallback process, but limits the range of timelines that can be retrieved." + inquiryUrl: "Contact URL" + inquiryUrlDescription: "Specify the URL of a web page that contains a contact form or the instance operators' contact information." _accountMigration: moveFrom: "Migrate another account to this one" moveFromSub: "Create alias to another account" @@ -1740,6 +1770,11 @@ _role: roleAssignedTo: "Assigned to manual roles" isLocal: "Local user" isRemote: "Remote user" + isCat: "Cat Users" + isBot: "Bot Users" + isSuspended: "Suspended user" + isLocked: "Private account" + isExplorable: "Account is discoverable" createdLessThan: "Less than X has passed since account creation" createdMoreThan: "More than X has passed since account creation" followersLessThanOrEq: "Has X or fewer followers" @@ -1811,6 +1846,7 @@ _plugin: installWarn: "Please do not install untrustworthy plugins." manage: "Manage plugins" viewSource: "View source" + viewLog: "Show log" _preferencesBackups: list: "Created backups" saveNew: "Save new backup" @@ -2004,7 +2040,6 @@ _2fa: registerTOTP: "Register authenticator app" step1: "First, install an authentication app (such as {a} or {b}) on your device." step2: "Then, scan the QR code displayed on this screen." - step2Click: "Clicking on this QR code will allow you to register 2FA to your security key or phone authenticator app." step2Uri: "Enter the following URI if you are using a desktop program" step3Title: "Enter an authentication code" step3: "Enter the authentication code (token) provided by your app to finish setup." @@ -2028,6 +2063,7 @@ _2fa: backupCodesDescription: "You can use these codes to gain access to your account in case of becoming unable to use your two-factor authentificator app. Each can only be used once. Please keep them in a safe place." backupCodeUsedWarning: "A backup code has been used. Please reconfigure two-factor authentification as soon as possible if you are no longer able to use it." backupCodesExhaustedWarning: "All backup codes have been used. Should you lose access to your two-factor authentification app, you will be unable to access this account. Please reconfigure two-factor authentification." + moreDetailedGuideHere: "Click here for a detailed guide" _permissions: "read:account": "View your account information" "write:account": "Edit your account information" @@ -2078,7 +2114,6 @@ _permissions: "read:admin:server-info": "View server info" "read:admin:show-moderation-log": "View moderation log" "read:admin:show-user": "View private user info" - "read:admin:show-users": "View private user info" "write:admin:suspend-user": "Suspend user" "write:admin:unset-user-avatar": "Remove user avatar" "write:admin:unset-user-banner": "Remove user banner" @@ -2296,6 +2331,7 @@ _play: title: "Title" script: "Script" summary: "Description" + visibilityDescription: "Putting it private means it won't be visible on your profile, but anyone that has the URL can still access it." _pages: newPage: "Create a new Page" editPage: "Edit this Page" @@ -2340,6 +2376,8 @@ _pages: section: "Section" image: "Images" button: "Button" + dynamic: "Dynamic Blocks" + dynamicDescription: "This block type has been removed. Please use {play} from now on." note: "Embedded note" _note: id: "Note ID" @@ -2369,6 +2407,7 @@ _notification: sendTestNotification: "Send test notification" notificationWillBeDisplayedLikeThis: "Notifications look like this" reactedBySomeUsers: "{n} users reacted" + likedBySomeUsers: "{n} users liked your note" renotedBySomeUsers: "Boosted by {n} users" followedBySomeUsers: "Followed by {n} users" flushNotification: "Clear notifications" @@ -2396,6 +2435,7 @@ _deck: alwaysShowMainColumn: "Always show main column" columnAlign: "Align columns" addColumn: "Add column" + newNoteNotificationSettings: "New note notification" configureColumn: "Column settings" swapLeft: "Swap with the left column" swapRight: "Swap with the right column" @@ -2691,3 +2731,21 @@ _reversi: _offlineScreen: title: "Offline - cannot connect to the server" header: "Unable to connect to the server" +_urlPreviewSetting: + title: "URL preview settings" + enable: "Enable URL preview" + timeout: "Time out when getting preview (ms)" + timeoutDescription: "If it takes longer than this value to get the preview, the preview won't be generated." + maximumContentLength: "Maximum Content-Length (bytes)" + maximumContentLengthDescription: "If Content-Length is higher than this value, the preview won't be generated." + requireContentLength: "Generate the preview only if we can get Content-Length" + requireContentLengthDescription: "If other server doesn't return Content-Length, the preview won't be generated." + userAgent: "User-Agent" + userAgentDescription: "Sets the User-Agent to be used when retrieving previews. If left blank, the default User-Agent will be used." + summaryProxy: "Endpoint for proxy to generate previews" + summaryProxyDescription: "Generate previews using Summaly Proxy, instead of Sharkey itself." + summaryProxyDescription2: "The following parameters are sent to the proxy as a query string. If the proxy does not support them, the values are ignored." +_mediaControls: + pip: "Picture in Picture" + playbackRate: "Playback Speed" + loop: "Loop playback" diff --git a/locales/es-ES.yml b/locales/es-ES.yml index c77773949f..209c2dec2d 100644 --- a/locales/es-ES.yml +++ b/locales/es-ES.yml @@ -235,7 +235,7 @@ done: "Terminado" processing: "Procesando" preview: "Vista previa" default: "Predeterminado" -defaultValueIs: "Predeterminado" +defaultValueIs: "Por defecto: {value}" noCustomEmojis: "No hay emojis personalizados" noJobs: "No hay trabajos" federating: "Federando" @@ -400,6 +400,7 @@ name: "Nombre" antennaSource: "Origen de la antena" antennaKeywords: "Palabras clave para recibir" antennaExcludeKeywords: "Palabras clave para excluir" +antennaExcludeBots: "Excluir bots" antennaKeywordsDescription: "Separar con espacios es una declaración AND, separar con una linea nueva es una declaración OR" notifyAntenna: "Notificar nueva nota" withFileAntenna: "Sólo notas con archivos adjuntados" @@ -494,6 +495,7 @@ emojiStyle: "Estilo de emoji" native: "Nativo" disableDrawer: "No mostrar los menús en cajones" showNoteActionsOnlyHover: "Mostrar acciones de la nota sólo al pasar el cursor" +showReactionsCount: "Mostrar el número de reacciones en las notas" noHistory: "No hay datos en el historial" signinHistory: "Historial de ingresos" enableAdvancedMfm: "Habilitar MFM avanzado" @@ -991,6 +993,7 @@ neverShow: "No mostrar de nuevo" remindMeLater: "Recordar después" didYouLikeMisskey: "¿Te gusta Misskey?" pleaseDonate: "{host} usa el software gratuito Misskey. Por favor ¡Considera donar al proyecto principal para que podamos continuar!" +correspondingSourceIsAvailable: "El código fuente correspondiente se encuentra disponible en {anchor}" roles: "Roles" role: "Rol" noRole: "Rol no encontrado" @@ -1042,6 +1045,7 @@ sensitiveWords: "Palabras sensibles" sensitiveWordsDescription: "La visibilidad de todas las notas que contienen cualquiera de las palabras configuradas serán puestas en \"Inicio\" automáticamente. Puedes enumerás varias separándolas con saltos de línea" sensitiveWordsDescription2: "Si se usan espacios se crearán expresiones AND y las palabras subsecuentes con barras inclinadas se convertirán en expresiones regulares." prohibitedWords: "Palabras explícitas" +prohibitedWordsDescription: "Activa un error cuando se intenta publicar una nota que contiene una o varias palabras prohibidas. Se pueden establecer varias palabras, una por línea." prohibitedWordsDescription2: "Si se usan espacios se crearán expresiones AND y las palabras subsecuentes con barras inclinadas se convertirán en expresiones regulares." hiddenTags: "Hashtags ocultos" hiddenTagsDescription: "Selecciona las etiquetas que no se mostrarán en tendencias. Una etiqueta por línea." @@ -1158,6 +1162,7 @@ showRenotes: "Mostrar renotas" edited: "Editado" notificationRecieveConfig: "Ajustes de Notificaciones" mutualFollow: "Os seguís mutuamente" +followingOrFollower: "Siguiendo o seguidor" fileAttachedOnly: "Solo notas con archivos" showRepliesToOthersInTimeline: "Mostrar respuestas a otros en la línea de tiempo" hideRepliesToOthersInTimeline: "Ocultar respuestas a otros en la línea de tiempo" @@ -1167,6 +1172,12 @@ confirmShowRepliesAll: "Esta operación es irreversible. ¿Confirmas que quieres confirmHideRepliesAll: "Esta operación es irreversible. ¿Confirmas que quieres ocultar tus respuestas a otros usuarios que sigues en tu línea de tiempo?" externalServices: "Servicios Externos" sourceCode: "Código fuente" +sourceCodeIsNotYetProvided: "El código fuente aún no está disponible. Contacta con el administrador para solucionarlo." +repositoryUrl: "URL del repositorio" +repositoryUrlDescription: "Si estás usando Misskey tal cual (sin cambios en el código fuente), entra en https://github.com/misskey-dev/misskey" +repositoryUrlOrTarballRequired: "Si no has publicado un repositorio aún, deberás publicar un tarball en su lugar. Mira el archivo .config/example.yml para más información." +feedback: "Comentarios" +feedbackUrl: "URL de comentarios" impressum: "Impressum" impressumUrl: "Impressum URL" impressumDescription: "En algunos países, como Alemania, la inclusión del operador de datos (el Impressum) es requerido legalmente para sitios web comerciales." @@ -1202,6 +1213,8 @@ soundWillBePlayed: "Se reproducirán efectos sonoros" showReplay: "Ver reproducción" replay: "Reproducir" replaying: "Reproduciendo" +endReplay: "Terminar reproducción" +copyReplayData: "Copiar datos de reproducción" ranking: "Clasificación" lastNDays: "Últimos {n} días" backToTitle: "Regresar al inicio" @@ -1209,9 +1222,32 @@ hemisphere: "Región" withSensitive: "Mostrar notas que contengan material sensible" userSaysSomethingSensitive: "La publicación de {name} contiene material sensible" enableHorizontalSwipe: "Deslice para cambiar de pestaña" +loading: "Cargando" surrender: "detener" +gameRetry: "Reintentar" +notUsePleaseLeaveBlank: "Dejar en blanco si no se usa" +useTotp: "Introduce la contraseña de un solo uso" +useBackupCode: "Usar códigos de respaldo" +launchApp: "Ejecutar la app" +useNativeUIForVideoAudioPlayer: "Usar la interfaz del navegador cuando se reproduce audio y vídeo" +keepOriginalFilename: "Mantener el nombre original del archivo" +noDescription: "No hay descripción" +alwaysConfirmFollow: "Confirmar siempre cuando se sigue a alguien" +_delivery: + stop: "Suspendido" + _type: + none: "Publicando" _bubbleGame: howToPlay: "Cómo jugar" + hold: "Mantener" + _score: + score: "Puntos" + scoreYen: "Cantidad de dinero ganada" + highScore: "Puntuación más alta" + maxChain: "Número máximo de cadenas" + yen: "{yen} Yenes" + estimatedQty: "{qty} Piezas" + scoreSweets: "{onigiriQtyWithUnit} Onigiris" _howToPlay: section1: "Ajuste la posición y deje caer el objeto en la caja" section2: "Cuando dos objetos del mismo tipo se tocan, cambian a otro tipo y consigues puntos" @@ -1329,7 +1365,7 @@ _serverSettings: _accountMigration: moveFrom: "Trasladar de otra cuenta a ésta" moveFromSub: "Crear un alias para otra cuenta." - moveFromLabel: "Cuenta desde la que se realiza el traslado:" + moveFromLabel: "Cuenta desde la que se realiza el traslado #{n}" moveFromDescription: "Si quieres transferir seguidores de otra cuenta a esta cuenta y trasladarlos, tendrás que crear un alias aquí. Asegúrate de crearlo antes de realizar el traslado. Introduce la cuenta desde la que estás moviendo los seguidores así: @person@instance.com" moveTo: "Mover esta cuenta a una nueva" moveToLabel: "Cuenta destino:" @@ -1588,8 +1624,11 @@ _achievements: description: "Tutorial completado" _bubbleGameExplodingHead: title: "🤯" + description: "El objeto más grande en el juego de burbujas" _bubbleGameDoubleExplodingHead: title: "Doble 🤯" + description: "Dos de los objetos más grandes en el juego de burbujas al mismo tiempo" + flavor: "Puedes llenar el bento un poco de esta forma 🤯 🤯." _role: new: "Crear rol" edit: "Editar rol" @@ -1630,6 +1669,7 @@ _role: gtlAvailable: "Explorar la línea de tiempo global" ltlAvailable: "Explorar la línea de tiempo local" canPublicNote: "Permitir la publicación" + mentionMax: "Número máximo de menciones en una nota" canInvite: "Puede crear códigos de invitación" inviteLimit: "Límite de invitaciones" inviteLimitCycle: "Enfriamiento del límite de invitaciones" @@ -1653,8 +1693,13 @@ _role: canUseTranslator: "Uso de traductor" avatarDecorationLimit: "Número máximo de decoraciones de avatar" _condition: + roleAssignedTo: "Asignado a roles manuales" isLocal: "Usuario local" isRemote: "Usuario remoto" + isCat: "Usuarios Gato" + isBot: "Usuarios Bot" + isSuspended: "Usuario suspendido" + isLocked: "Cuentas privadas" createdLessThan: "Menos de X han pasado desde la creación de la cuenta" createdMoreThan: "Más de X han pasado desde la creación de la cuenta" followersLessThanOrEq: "Tiene X o menos seguidores" @@ -1724,6 +1769,7 @@ _plugin: installWarn: "Por favor no instale plugins que no son de confianza" manage: "Gestionar plugins" viewSource: "Ver la fuente" + viewLog: "Ver log" _preferencesBackups: list: "Respaldos creados" saveNew: "Guardar nuevo respaldo" @@ -1753,6 +1799,8 @@ _aboutMisskey: contributors: "Principales colaboradores" allContributors: "Todos los colaboradores" source: "Código fuente" + original: "Original" + thisIsModifiedVersion: "{name} usa una versión modificada de Misskey." translation: "Traducir Misskey" donate: "Donar a Misskey" morePatrons: "Muchas más personas nos apoyan. Muchas gracias🥰" @@ -1911,7 +1959,6 @@ _2fa: registerTOTP: "Registrar aplicación autenticadora" step1: "Primero, instale en su dispositivo la aplicación de autenticación {a} o {b} u otra." step2: "Luego, escanee con la aplicación el código QR mostrado en pantalla." - step2Click: "Clicking on this QR code will allow you to register 2FA to your security key or phone authenticator app.\nTocar este código QR te permitirá registrar la autenticación 2FA a tu llave de seguridad o aplicación autenticadora." step2Uri: "Si usas una aplicación de escritorio, introduce en ella la siguiente URL." step3Title: "Ingresa un código de autenticación" step3: "Para terminar, ingrese el token mostrado en la aplicación." @@ -1935,6 +1982,7 @@ _2fa: backupCodesDescription: "En caso de que no puedas usar tu aplicación de autenticación, podrás usar los códigos de respaldo que figuran abajo para acceder a tu cuenta. Asegúrate de guardar en lugar seguro los códigos de respaldo. Cada uno de los códigos de respaldo es de un solo uso." backupCodeUsedWarning: "Has usado todos los códigos de respaldo. Si dejas de tener acceso a tu aplicación de autenticación, no podrás volver a iniciar sesión en tu cuenta. Por favor, reconfigura tu aplicación de autenticación lo antes posible." backupCodesExhaustedWarning: "Has usado todos los códigos de respaldo. Si dejas de tener acceso a tu aplicación de autenticación, no podrás volver a iniciar sesión en la cuenta que figura arriba. Por favor, reconfigura tu aplicación de autenticación lo antes posible." + moreDetailedGuideHere: "Guía detallada" _permissions: "read:account": "Ver información de la cuenta" "write:account": "Editar información de la cuenta" @@ -1976,6 +2024,7 @@ _permissions: "write:admin:delete-account": "Eliminar cuentas de usuario" "write:admin:delete-all-files-of-a-user": "Eliminar todos los archivos de un usuario" "read:admin:index-stats": "Ver datos indexados" + "read:admin:table-stats": "Ver estadísticas de las tablas de la base de datos" "read:admin:user-ips": "Ver dirección IP de usuario" "read:admin:meta": "Ver metadatos de la instancia" "write:admin:reset-password": "Restablecer contraseñas de usuario" @@ -1984,7 +2033,6 @@ _permissions: "read:admin:server-info": "Ver información del servidor" "read:admin:show-moderation-log": "Ver log de moderación" "read:admin:show-user": "Ver información privada de usuario" - "read:admin:show-users": "Ver información privada de usuario" "write:admin:suspend-user": "Suspender cuentas de usuario" "write:admin:unset-user-avatar": "Quitar avatares de usuario" "write:admin:unset-user-banner": "Quitar banner de usuarios" @@ -2196,6 +2244,7 @@ _play: title: "Título" script: "Script" summary: "Descripción" + visibilityDescription: "Poniéndola como privada significa que no será visible en tu perfil, pero cualquiera que tenga la URL aún podrá acceder a ella." _pages: newPage: "Crear página" editPage: "Editar página" @@ -2240,6 +2289,8 @@ _pages: section: "Sección" image: "Imagen" button: "Botón" + dynamic: "Bloques Dinámicos" + dynamicDescription: "Los bloques dinámicos están obsoletos. A partir de ahora, utiliza {play} por favor." note: "Nota embebida" _note: id: "Id de la nota" @@ -2449,3 +2500,11 @@ _reversi: reversi: "Reversi" won: "{name} ha ganado" total: "Total" +_urlPreviewSetting: + timeout: "Timeout de la carga de vista previa de las URLs (ms)" + maximumContentLength: "Content-Length Máximo (bytes)" + userAgent: "User-Agent" +_mediaControls: + pip: "Picture in Picture" + playbackRate: "Velocidad de reproducción" + loop: "Reproducción en bucle" diff --git a/locales/fr-FR.yml b/locales/fr-FR.yml index 6a32f75231..22a9e2449f 100644 --- a/locales/fr-FR.yml +++ b/locales/fr-FR.yml @@ -129,7 +129,7 @@ overwriteFromPinnedEmojisForReaction: "Remplacer par les émojis épinglés pour overwriteFromPinnedEmojis: "Remplacer par les émojis épinglés globalement" reactionSettingDescription2: "Déplacer pour réorganiser, cliquer pour effacer, utiliser « + » pour ajouter." rememberNoteVisibility: "Se souvenir de la visibilité des notes" -attachCancel: "Supprimer le fichier attaché" +attachCancel: "Supprimer le fichier joint" deleteFile: "Fichier supprimé" markAsSensitive: "Marquer comme sensible" unmarkAsSensitive: "Supprimer le marquage comme sensible" @@ -400,6 +400,7 @@ name: "Nom" antennaSource: "Source de l’antenne" antennaKeywords: "Mots clés à recevoir" antennaExcludeKeywords: "Mots clés à exclure" +antennaExcludeBots: "Exclure les comptes robot" antennaKeywordsDescription: "Séparer avec des espaces pour la condition AND. Séparer avec un saut de ligne pour une condition OR." notifyAntenna: "Me notifier pour les nouvelles notes" withFileAntenna: "Notes ayant des fichiers joints uniquement" @@ -494,6 +495,7 @@ emojiStyle: "Style des émojis" native: "Natif" disableDrawer: "Les menus ne s'affichent pas dans le tiroir" showNoteActionsOnlyHover: "Afficher les actions de note uniquement au survol" +showReactionsCount: "Afficher le nombre de réactions des notes" noHistory: "Pas d'historique" signinHistory: "Historique de connexion" enableAdvancedMfm: "Activer la MFM avancée" @@ -541,6 +543,7 @@ objectStorageUseSSLDesc: "Désactivez cette option si vous n'utilisez pas HTTPS objectStorageUseProxy: "Se connecter via proxy" objectStorageUseProxyDesc: "Désactivez cette option si vous n'utilisez pas de proxy pour la connexion API" objectStorageSetPublicRead: "Régler sur « public » lors de l'envoi" +s3ForcePathStyleDesc: "Si s3ForcePathStyle est activé, le nom du compartiment doit être spécifié comme une partie du chemin de l'URL plutôt que le nom d'hôte. Il faudra peut-être l'activer lors de l'utilisation d'une instance de Minio autohébergée, etc." serverLogs: "Journal du serveur" deleteAll: "Supprimer tout" showFixedPostForm: "Afficher le formulaire de publication en haut du fil d'actualité" @@ -655,7 +658,7 @@ testEmail: "Tester la distribution de courriel" wordMute: "Filtre de mots" hardWordMute: "Filtre de mots dur" regexpError: "Erreur d’expression régulière" -regexpErrorDescription: "Une erreur s'est produite dans l'expression régulière sur la ligne {ligne} de votre mot muet {tab} :" +regexpErrorDescription: "Une erreur s'est produite dans l'expression régulière sur la ligne {line} de votre mot muet {tab} :" instanceMute: "Instance en sourdine" userSaysSomething: "{name} a dit quelque chose" makeActive: "Activer" @@ -675,6 +678,7 @@ useGlobalSettingDesc: "S'il est activé, les paramètres de notification de votr other: "Autre" regenerateLoginToken: "Régénérer le jeton de connexion" regenerateLoginTokenDescription: "Générer un nouveau jeton d'authentification. Cette opération ne devrait pas être nécessaire ; lors de la génération d'un nouveau jeton, tous les appareils seront déconnectés. " +theKeywordWhenSearchingForCustomEmoji: "Ce mot-clé est utilisé lors de la recherche des émojis personnalisés." setMultipleBySeparatingWithSpace: "Vous pouvez en définir plusieurs, en les séparant par des espaces." fileIdOrUrl: "ID du fichier ou URL" behavior: "Comportement" @@ -989,6 +993,7 @@ neverShow: "Ne plus afficher" remindMeLater: "Peut-être plus tard" didYouLikeMisskey: "Avez-vous aimé Misskey ?" pleaseDonate: "Misskey est le logiciel libre utilisé par {host}. Merci de faire un don pour que nous puissions continuer à le développer !" +correspondingSourceIsAvailable: "Le code source correspondant est disponible à {anchor}" roles: "Rôles" role: "Rôles" noRole: "Aucun rôle" @@ -1003,6 +1008,7 @@ youCannotCreateAnymore: "Vous avez atteint la limite de création." cannotPerformTemporary: "Temporairement indisponible" cannotPerformTemporaryDescription: "Temporairement indisponible puisque le nombre d'opérations dépasse la limite. Veuillez patienter un peu, puis réessayer." invalidParamError: "Paramètres invalides" +invalidParamErrorDescription: "Les paramètres de la requête sont invalides. Il s'agit généralement d'un bogue, mais cela peut aussi être causé par un excès de caractères ou quelque chose de similaire." permissionDeniedError: "Opération refusée" permissionDeniedErrorDescription: "Ce compte n'a pas la permission d'effectuer cette opération." preset: "Préréglage" @@ -1016,6 +1022,7 @@ thisPostMayBeAnnoyingCancel: "Annuler" thisPostMayBeAnnoyingIgnore: "Publier quand-même" collapseRenotes: "Réduire les renotes déjà vues" internalServerError: "Erreur interne du serveur" +internalServerErrorDescription: "Une erreur inattendue s'est produite sur le serveur." copyErrorInfo: "Copier les détails de l’erreur" joinThisServer: "S'inscrire à cette instance" exploreOtherServers: "Trouver une autre instance" @@ -1035,8 +1042,10 @@ nonSensitiveOnlyForLocalLikeOnlyForRemote: "Non sensibles seulement (mentions j' rolesAssignedToMe: "Rôles attribués à moi" resetPasswordConfirm: "Souhaitez-vous réinitialiser votre mot de passe ?" sensitiveWords: "Mots sensibles" +sensitiveWordsDescription: "Définir la visibilité des notes contenant un mot défini ici au fil principal automatiquement. Vous pouvez définir plusieurs valeurs en les séparant par des sauts de ligne." sensitiveWordsDescription2: "Séparer par une espace pour créer une expression AND ; entourer de barres obliques pour créer une expression régulière." prohibitedWords: "Mots interdits" +prohibitedWordsDescription: "Publier une note contenant un mot défini ici produira une erreur. Vous pouvez définir plusieurs valeurs en les séparant par des sauts de ligne." prohibitedWordsDescription2: "Séparer par une espace pour créer une expression AND ; entourer de barres obliques pour créer une expression régulière." hiddenTags: "Hashtags cachés" hiddenTagsDescription: "Les hashtags définis ne s'afficheront pas dans les tendances. Vous pouvez définir plusieurs hashtags en faisant un saut de ligne." @@ -1082,9 +1091,11 @@ pleaseConfirmBelowBeforeSignup: "Pour vous inscrire sur cette instance, vous dev pleaseAgreeAllToContinue: "Pour continuer, veuillez accepter tous les champs ci-dessus." continue: "Continuer" preservedUsernames: "Noms d'utilisateur·rice réservés" +preservedUsernamesDescription: "Énumérez les noms d'utilisateur à réserver, séparés par des nouvelles lignes. Les noms d'utilisateur spécifiés ici ne seront plus utilisables lors de la création d'un compte, sauf la création manuelle par un administrateur. De plus, les comptes existants ne seront pas affectés." createNoteFromTheFile: "Rédiger une note de ce fichier" archive: "Archive" channelArchiveConfirmTitle: "Voulez-vous vraiment archiver {name} ?" +channelArchiveConfirmDescription: "Une fois archivé, le canal n'apparaîtra plus dans la liste des canaux ni dans les résultats de recherche, et la publication des nouvelles notes sera impossible." thisChannelArchived: "Ce canal a été archivé." displayOfNote: "Affichage de la note" initialAccountSetting: "Configuration initiale du profil" @@ -1113,6 +1124,8 @@ createWithOptions: "Options" createCount: "Quantité à créer" inviteCodeCreated: "Code d'invitation créé" inviteLimitExceeded: "Vous avez atteint la limite de codes d'invitation que vous pouvez générer." +createLimitRemaining: "Codes d'invitation pouvant être créés : {limit} restants" +inviteLimitResetCycle: "Vous pouvez créer jusqu'à {limit} codes d'invitation en {time}." expirationDate: "Date d’expiration" noExpirationDate: "Ne pas expirer" inviteCodeUsedAt: "Code d'invitation utilisé à" @@ -1132,11 +1145,14 @@ forYou: "Pour vous" currentAnnouncements: "Annonces actuelles" pastAnnouncements: "Annonces passées" youHaveUnreadAnnouncements: "Il y a des annonces non lues." +useSecurityKey: "Suivez les instructions de votre navigateur ou de votre appareil pour utiliser une clé de sécurité ou une clé d'accès." replies: "Réponses" renotes: "Renotes" loadReplies: "Inclure les réponses" loadConversation: "Afficher la conversation" pinnedList: "Liste épinglée" +keepScreenOn: "Garder l'écran toujours allumé" +verifiedLink: "Votre propriété de ce lien a été vérifiée" notifyNotes: "Notifier à propos des nouvelles notes" unnotifyNotes: "Ne pas notifier pour la publication des notes" authentication: "Authentification" @@ -1146,6 +1162,7 @@ showRenotes: "Afficher les renotes" edited: "Modifié" notificationRecieveConfig: "Paramètres des notifications" mutualFollow: "Abonnement mutuel" +followingOrFollower: "Abonnement ou abonné" fileAttachedOnly: "Avec fichiers joints seulement" showRepliesToOthersInTimeline: "Afficher les réponses aux autres dans le fil" hideRepliesToOthersInTimeline: "Masquer les réponses aux autres dans le fil" @@ -1201,10 +1218,16 @@ ranking: "Classement" lastNDays: "Derniers {n} jours" backToTitle: "Retourner au titre" hemisphere: "Votre région" +withSensitive: "Afficher les notes contenant des fichiers joints sensibles" +userSaysSomethingSensitive: "Note de {name} contenant des fichiers joints sensibles" enableHorizontalSwipe: "Glisser pour changer d'onglet" loading: "Chargement en cours" surrender: "Annuler" gameRetry: "Réessayer" +_delivery: + stop: "Suspendu·e" + _type: + none: "Publié" _bubbleGame: howToPlay: "Comment jouer" hold: "Réserver" @@ -1212,15 +1235,25 @@ _bubbleGame: score: "Score" scoreYen: "Montant gagné" highScore: "Meilleur score" + maxChain: "Nombre maximum de chaînes" yen: "{yen} yens" + estimatedQty: "{qty} pièces" _announcement: forExistingUsers: "Pour les utilisateurs existants seulement" + needConfirmationToRead: "Exiger la confirmation de la lecture" + needConfirmationToReadDescription: "Si activé, afficher un dialogue de confirmation quand l'annonce est marquée comme lue. Aussi, elle sera exclue de « marquer tout comme lu » ." + end: "Archiver l'annonce" + tooManyActiveAnnouncementDescription: "Un grand nombre d'annonces actives peut baisser l'expérience utilisateur. Considérez d'archiver les annonces obsolètes." readConfirmTitle: "Marquer comme lu ?" + readConfirmText: "Cela marquera le contenu de « {title} » comme lu." shouldNotBeUsedToPresentPermanentInfo: "Puisque cela pourrait nuire considérablement à l'expérience utilisateur pour les nouveaux utilisateurs, il est recommandé d'utiliser les annonces pour afficher des informations temporaires plutôt que des informations persistantes." dialogAnnouncementUxWarn: "Avoir deux ou plus annonces de style dialogue en même temps pourrait nuire considérablement à l'expérience utilisateur. Veuillez les utiliser avec caution." silence: "Ne pas me notifier" silenceDescription: "Si activée, vous ne recevrez pas de notifications sur les annonces et n'aurez pas besoin de les marquer comme lues." _initialAccountSetting: + accountCreated: "Votre compte a été créé avec succès !" + letsStartAccountSetup: "Procédons au réglage initial du compte." + letsFillYourProfile: "Commençons par configurer votre profil !" profileSetting: "Paramètres du profil" privacySetting: "Paramètres de confidentialité" initialAccountSettingCompleted: "Configuration du profil terminée avec succès !" @@ -1288,7 +1321,7 @@ _initialTutorial: doItToContinue: "Marquez le fichier joint comme sensible pour procéder." _done: title: "Le tutoriel est terminé ! 🎉" - description: "Les fonctionnalités introduites ici ne sont que quelques-unes. Pour savoir plus sur l'utilisation de Misskey, veuillez consulter {lien}." + description: "Les fonctionnalités introduites ici ne sont que quelques-unes. Pour savoir plus sur l'utilisation de Misskey, veuillez consulter {link}." _timelineDescription: home: "Sur le fil principal, vous pouvez voir les notes des utilisateurs auxquels vous êtes abonné·e." local: "Sur le fil local, vous pouvez voir les notes de tous les utilisateurs sur cette instance." @@ -1449,7 +1482,7 @@ _role: edit: "Modifier le rôle" name: "Nom du rôle" description: "Description du rôle" - permission: "Rôle et autorisations" + permission: "Autorisations du rôle" assignTarget: "Attribuer" manual: "Manuel" manualRoles: "Rôles manuels" @@ -1984,7 +2017,7 @@ _notification: unreadAntennaNote: "Antenne {name}" roleAssigned: "Rôle attribué" emptyPushNotificationMessage: "Les notifications push ont été mises à jour" - achievementEarned: "Accomplissement" + achievementEarned: "Accomplissement déverrouillé" testNotification: "Tester la notification" reactedBySomeUsers: "{n} utilisateur·rice·s ont réagi" renotedBySomeUsers: "{n} utilisateur·rice·s ont renoté" @@ -2001,7 +2034,7 @@ _notification: receiveFollowRequest: "Demande d'abonnement reçue" followRequestAccepted: "Demande d'abonnement acceptée" roleAssigned: "Rôle reçu" - achievementEarned: "Accomplissement" + achievementEarned: "Déverrouillage d'accomplissement" app: "Notifications provenant des apps" _actions: followBack: "Suivre" @@ -2139,4 +2172,5 @@ _dataSaver: title: "Mise en évidence du code" description: "Si la notation de mise en évidence du code est utilisée, par exemple dans la MFM, elle ne sera pas chargée tant qu'elle n'aura pas été tapée. La mise en évidence du code nécessite le chargement du fichier de définition de chaque langue à mettre en évidence, mais comme ces fichiers ne sont plus chargés automatiquement, on peut s'attendre à une réduction du trafic de données." _reversi: + waitingBoth: "Préparez-vous" total: "Total" diff --git a/locales/hr-HR.yml b/locales/hr-HR.yml index 881aa8464e..9cfebdd01a 100644 --- a/locales/hr-HR.yml +++ b/locales/hr-HR.yml @@ -3,4 +3,3 @@ _lang_: "japanski" ok: "OK" gotIt: "Razumijem" cancel: "otkazati" - diff --git a/locales/ht-HT.yml b/locales/ht-HT.yml index 1698c9f280..e3595c79b6 100644 --- a/locales/ht-HT.yml +++ b/locales/ht-HT.yml @@ -16,4 +16,3 @@ _2fa: renewTOTPCancel: "Sispann" _widgets: profile: "pwofil" - diff --git a/locales/hu-HU.yml b/locales/hu-HU.yml index 2f7006484a..023a91494d 100644 --- a/locales/hu-HU.yml +++ b/locales/hu-HU.yml @@ -102,4 +102,3 @@ _deck: _columns: notifications: "Értesítések" tl: "Idővonal" - diff --git a/locales/id-ID.yml b/locales/id-ID.yml index b638d7991f..01fa02e678 100644 --- a/locales/id-ID.yml +++ b/locales/id-ID.yml @@ -108,11 +108,14 @@ enterEmoji: "Masukkan emoji" renote: "Renote" unrenote: "Hapus renote" renoted: "Telah direnote" +renotedToX: "{name} telah merenote" cantRenote: "Postingan ini tidak dapat direnote" cantReRenote: "Renote tidak dapat direnote" quote: "Kutip" inChannelRenote: "Hanya renote dalam kanal" inChannelQuote: "Hanya kutip dalam kanal" +renoteToChannel: "Renote ke kanal" +renoteToOtherChannel: "Renote ke kanal lainnya" pinnedNote: "Catatan yang disematkan" pinned: "Sematkan ke profil" you: "Kamu" @@ -400,6 +403,7 @@ name: "Nama" antennaSource: "Sumber Antenna" antennaKeywords: "Kata kunci yang diterima" antennaExcludeKeywords: "Kata kunci yang dikecualikan" +antennaExcludeBots: "Kecualikan akun bot" antennaKeywordsDescription: "Pisahkan dengan spasi untuk kondisi AND. Pisahkan dengan baris baru untuk kondisi OR." notifyAntenna: "Beritahu untuk catatan baru" withFileAntenna: "Hanya tampilkan catatan dengan berkas yang dilampirkan" @@ -467,6 +471,7 @@ retype: "Masukkan ulang" noteOf: "Catatan milik {user}" quoteAttached: "Dikutip" quoteQuestion: "Apakah kamu ingin menambahkan kutipan?" +attachAsFileQuestion: "Teks dalam papan klip terlalu panjang. Apakah kamu ingin melampirkannya sebagai berkas teks?" noMessagesYet: "Tidak ada pesan" newMessageExists: "Kamu mendapatkan pesan baru" onlyOneFileCanBeAttached: "Kamu hanya dapat melampirkan satu berkas ke dalam pesan" @@ -494,6 +499,7 @@ emojiStyle: "Gaya emoji" native: "Native" disableDrawer: "Jangan gunakan menu bergaya laci" showNoteActionsOnlyHover: "Hanya tampilkan aksi catatan saat ditunjuk" +showReactionsCount: "Lihat jumlah reaksi dalam catatan" noHistory: "Tidak ada riwayat" signinHistory: "Riwayat masuk" enableAdvancedMfm: "Nyalakan MFM tingkat lanjut" @@ -991,6 +997,7 @@ neverShow: "Jangan tampilkan lagi" remindMeLater: "Mungkin nanti" didYouLikeMisskey: "Apakah kamu mulai menyukai Misskey?" pleaseDonate: "{host} menggunakan perangkat lunak bebas yaitu Misskey. Kami sangat mengapresiasi sekali donasi dari kamu agar pengembangan Misskey tetap dapat berlanjut!" +correspondingSourceIsAvailable: "Sumber kode terkait tersedia di {anchor}" roles: "Peran" role: "Peran" noRole: "Peran tidak temukan" @@ -1042,6 +1049,7 @@ sensitiveWords: "Kata sensitif" sensitiveWordsDescription: "Visibilitas dari semua catatan mengandung kata yang telah diatur akan dijadikan \"Beranda\" secara otomatis. Kamu dapat mendaftarkan kata tersebut lebih dari satu dengan menuliskannya di baris baru." sensitiveWordsDescription2: "Menggunakan spasi akan membuat ekspresi AND dan kata kunci disekitarnya dengan garis miring akan mengubahnya menjadi ekspresi reguler." prohibitedWords: "Kata yang dilarang" +prohibitedWordsDescription: "Menyalakan kesalahan ketika mencoba untuk memposting catatan dengan set kata-kata yang termasuk. Beberapa kata dapat diatur dan dipisahkan dengan baris baru." prohibitedWordsDescription2: "Menggunakan spasi akan membuat ekspresi AND dan kata kunci disekitarnya dengan garis miring akan mengubahnya menjadi ekspresi reguler." hiddenTags: "Tagar tersembunyi" hiddenTagsDescription: "Pilih tanda yang mana akan tidak diperlihatkan dalam daftar tren.\nTanda lebih dari satu dapat didaftarkan dengan tiap baris." @@ -1158,6 +1166,7 @@ showRenotes: "Tampilkan renote" edited: "Telah disunting" notificationRecieveConfig: "Pengaturan notifikasi" mutualFollow: "Saling mengikuti" +followingOrFollower: "Mengikuti atau pengikut" fileAttachedOnly: "Hanya catatan dengan berkas" showRepliesToOthersInTimeline: "Tampilkan balasan ke pengguna lain dalam lini masa" hideRepliesToOthersInTimeline: "Sembunyikan balasan ke orang lain dari lini masa" @@ -1167,6 +1176,12 @@ confirmShowRepliesAll: "Operasi ini tidak dapat diubah. Apakah kamu yakin untuk confirmHideRepliesAll: "Operasi ini tidak dapat diubah. Apakah kamu yakin untuk menyembunyikan balasan ke lainnya dari semua orang yang kamu ikuti di lini masa?" externalServices: "Layanan eksternal" sourceCode: "Sumber kode" +sourceCodeIsNotYetProvided: "Sumber kode belum tersedia. Hubungi admin untuk memperbaiki masalah ini." +repositoryUrl: "URL Repositori" +repositoryUrlDescription: "Jika kamu menggunakan Misskey begitu saja (tanpa ada perubahan dalam kode sumber), masukkan https://github.com/misskey-dev/misskey" +repositoryUrlOrTarballRequired: "Apabila kamu masih mempublikasikan repositori, kamu setidaknya harus menyediakan berkas tarball. Lihat .config/example.yml untuk informasi lebih lanjut." +feedback: "Umpan balik" +feedbackUrl: "URL Umpan balik" impressum: "Impressum" impressumUrl: "Tautan Impressum" impressumDescription: "Pada beberapa negara seperti Jerman, inklusi dari informasi kontak operator (sebuah Impressum) diperlukan secara legal untuk situs web komersil." @@ -1202,6 +1217,8 @@ soundWillBePlayed: "Suara yang akan dimainkan" showReplay: "Lihat tayangan ulang" replay: "Tayangan ulang" replaying: "Menayangkan Ulang" +endReplay: "Keluat dari tayangan ulang" +copyReplayData: "Salin data tayangan ulang" ranking: "Peringkat" lastNDays: "{n} hari terakhir" backToTitle: "Ke Judul" @@ -1209,11 +1226,43 @@ hemisphere: "Letak kamu tinggal" withSensitive: "Lampirkan catatan dengan berkas sensitif" userSaysSomethingSensitive: "Postingan oleh {name} mengandung konten sensitif" enableHorizontalSwipe: "Geser untuk mengganti tab" +loading: "Memuat..." surrender: "Batalkan" +gameRetry: "Coba lagi" +notUsePleaseLeaveBlank: "Kosongi bila tidak digunakan" +useTotp: "Gunakan TOTP" +useBackupCode: "Gunakan kode cadangan" +launchApp: "Luncurkan Aplikasi" +useNativeUIForVideoAudioPlayer: "Gunakan antarmuka peramban ketika memainkan video dan audio" +keepOriginalFilename: "Simpan nama berkas asli" +keepOriginalFilenameDescription: "Apabila pengaturan ini dimatikan, nama berkas akan diganti dengan string acak secara otomatis ketika kamu mengunggah berkas." +noDescription: "Tidak ada deskripsi" +alwaysConfirmFollow: "Selalu konfirmasi ketika mengikuti" +inquiry: "Hubungi kami" +_delivery: + status: "Status pengiriman" + stop: "Ditangguhkan" + resume: "Lanjutkan pengiriman" + _type: + none: "Sedang menyiarkan langsung" + manuallySuspended: "Ditangguhkan manual" + goneSuspended: "Sedang ditangguhkan untuk penghapusan peladen" + autoSuspendedForNotResponding: "Sedang ditangguhkan karena peladen tidak menjawab" _bubbleGame: howToPlay: "Cara bermain" + hold: "Tahan" + _score: + score: "Skor" + scoreYen: "Jumlah uang didapat" + highScore: "Skor tertinggi" + maxChain: "Jumlah skor berantai" + yen: "{yen} Yen" + estimatedQty: "{qty} buah" + scoreSweets: "{onigiriQtyWithUnit} onigiri" _howToPlay: section1: "Atur posisi dan jatuhkan obyek ke dalam kotak." + section2: "Ketika dua obyek menyentuh tipe yang sama satu sama lain, obyek tersebut akan berganti dan kamu mendapatkan poin skor." + section3: "Permainan berakhir jika obyek memenuhi kotak. Capai skor tertinggi dengan menggabungkan obyek bersama sambil menghindari obyek tersebut memenuhi kotak permainan!" _announcement: forExistingUsers: "Hanya pengguna yang telah ada" forExistingUsersDescription: "Pengumuman ini akan dimunculkan ke pengguna yang sudah ada dari titik waktu publikasi jika dinyalakan. Apabila dimatikan, mereka yang baru mendaftar setelah publikasi ini akan juga melihatnya." @@ -1257,26 +1306,59 @@ _initialTutorial: reply: "Klik pada tombol ini untuk membalas ke sebuah pesan. Bisa juga untuk membalas ke sebuah balasan dan melanjutkannya seperti percakapan selayaknya utas." renote: "Kamu dapat membagikan catatan ke lini masa milikmu. Kamu juga dapat mengutipnya dengan komentarmu." reaction: "Kamu dapat menambahkan reaksi ke Catatan. Detil lebih lanjut akan dijelaskan di halaman berikutnya." + menu: "Kamu dapat melihat detil catatan, menyalin tautan, dan melakukan aksi lainnya." _reaction: title: "Apa itu Reaksi?" + description: "Catatan dapat direaksi dengan berbagai emoji. Reaksi memperbolehkan kamu untuk mengekspresikan nuansa yang tidak dapat disampaikan hanya dengan sebuah \"suka\"." + letsTryReacting: "Reaksi dapat ditambahkan dengan mengklik tombol '{reaction}' pada catatan. Coba lakukan mereaksi contoh catatan ini!" + reactToContinue: "Tambahkan reaksi untuk melanjutkan." + reactNotification: "Kamu akan menerima notifikasi real0time ketika seseorang mereaksi catatan kamu." + reactDone: "Kamu dapat mengurungkan reaksi dengan menekan tombol '{undo}'." _timeline: title: "Konsep Lini Masa" + description1: "Misskey menyediakan berbagai lini masa sesuai dengan penggunaan (beberapa mungkin tidak tersedia karena bergantung dengan kebijakan peladen)." + home: "Kamu dapat melihat catatan dari akun yang kamu ikuti." + local: "Kamu dapat melihat catatan dari semua pengguna yang ada pada peladen ini." + social: "Catatan dari linimasa Beranda dan Lokal akan ditampilkan." + global: "Kamu dapat melihat catatan dari semua peladen yang terhubung." + description2: "Kamu dapat mengganti linimasa di bagian atas layar kamu kapan saja." + description3: "Sebagai tambahan, terdapat juga linimasa daftar dan linimasa kanal. Untuk detil lebih lanjut, silahkan melihat ke tautan berikut: {link}." _postNote: title: "Pengaturan posting Catatan" + description1: "Ketika memposting catatan ke Misskey, terdapat beberapa opsi yang tersedia. Form posting terlihat seperti ini." _visibility: + description: "Kamu dapat membatasi siapa yang dapat melihat catatan kamu." public: "Perlihatkan catatan ke semua pengguna." home: "Hanya publik ke lini masa Beranda. Pengguna yang mengunjungi profilmu melalui pengikut dan renote dapat melihatnya." followers: "Perlihatkan ke pengikut saja. Hanya pengikut yang dapat melihat postinganmu dan tidak dapat direnote oleh siapapun." direct: "Hanya perlihatkan ke pengguna spesifik dan penerima akan diberi tahu. Dapat juga digunakan sebagai alternatif dari pesan langsung." + doNotSendConfidencialOnDirect1: "Hati-hati ketika mengirim informasi yang sensitif!" + doNotSendConfidencialOnDirect2: "Admin dari peladen dapat melihat apa yang kamu tulis. Hati-hati dengan informasi sensitif ketika mengirimkan catatan langsung kepada pengguna pada peladen yang tidak dipercaya." + localOnly: "Memposting dengan opsi ini tidak akan memfederasi catatan ke peladen lain. Pengguna pada peladen lain tidak akan dapat melihat catatan ini secara langsung, meskipun dengan pengaturan visibilitas yang sudah diatur di atas." _cw: title: "Peringatan Konten (CW)" + description: "Alih-alih isinya, konten yang ditulis dalam kolom 'komentar' akan ditampilkan. Menekan 'Selebihnya' akan menampilkan isi konten." _exampleNote: cw: "Peringatan: Bikin Lapar!" note: "Baru aja makan donat berlapis coklat 🍩😋" + useCases: "Fungsi ini digunakan ketika mengikutik panduan peladen untuk catatan yang dibutuhkan atau untuk membatasi diri dari teks sensitif atau spoiler." _howToMakeAttachmentsSensitive: title: "Bagaimana menandai lampiran sebagai sensitif?" + description: "Fungsi ini digunakan untuk lampiran yang dibutuhkan oleh panduan peladen atau sesuatu yang seharusnya tidak boleh dibiarkan begitu saja dengan cara menambahkan penanda \"sensitif\"." + tryThisFile: "Coba tandai gambar yang dilampirkan pada form ini sebagai sensitif!" + _exampleNote: + note: "Ups, kesalahan banget buka penutup wadah natto..." + method: "Untuk menandai lampiran sebagai sensitif, klik gambar pada berkas, buka menu, lalu klik \"Tandai sebagai sensitif\"." + sensitiveSucceeded: "Ketika melampirkan berkas, mohon atur sensitifitas sesuai dengan panduan peladen." + doItToContinue: "Tandai berkas terlampir sebagai sensitif untuk melanjutkan." _done: title: "Kamu telah menyelesaikan tutorial! 🎉" + description: "Fungsi yang diperkenalkan di sini merupakan sebagian kecil dari fitur yang ada. Untuk pemahaman lebih detil dalam menggunakan Misskey, kamu dapat merujuk ke {link}." +_timelineDescription: + home: "Pada linimasa Beranda, kamu dapat melihat catatan dari akun yang kamu ikuti." + local: "Pada linimasa Lokal, kamu dapat melihat catatan dari semua pengguna yang ada pada peladen ini." + social: "Linimasa sosial menampilkan catatan dari kedua linimasa Beranda dan Lokal." + global: "Pada linimasa Global, kamu dapat melihat catatan dari semua peladen yang terhubung." _serverRules: description: "Daftar peraturan akan ditampilkan sebelum pendaftaran. Mengatur ringkasan dari Syarat dan Ketentuan sangat direkomendasikan." _serverSettings: @@ -1288,6 +1370,9 @@ _serverSettings: manifestJsonOverride: "Ambil alih manifest.json" shortName: "Nama pendek" shortNameDescription: "Inisial untuk nama instansi yang dapat ditampilkan apabila nama lengkap resmi terlalu panjang." + fanoutTimelineDescription: "Dapat meningkatkan performa dalam pengambilan data linimasa dan mengurangi beban pada database ketika dinyalakan. Sebagai gantinya, penggunaan memory pada Redis akan meningkan. Pertimbangkan untuk menonaktifkan fitur ini jika mengalami kekurangan memori pada server atau menyebabkan server tidak stabil." + fanoutTimelineDbFallback: "Fallback ke database" + fanoutTimelineDbFallbackDescription: "Ketika diaktifkan, lini masa akan fallback ke database untuk melakukan kueri tambahan apabila linimasa tidak disimpan dalam cache. Menonaktifkan ini dapat mengurangi beban server dengan mengeliminasi proses fallback, namun dapat berakibat membatasi jarak data dari lini masa yang dapat diambil." _accountMigration: moveFrom: "Pindahkan akun lain ke akun ini" moveFromSub: "Buat alias ke akun lain" @@ -1545,6 +1630,16 @@ _achievements: _smashTestNotificationButton: title: "Tes overflow" description: "Picu tes notifikasi secara berulang dalam waktu yang sangat pendek" + _tutorialCompleted: + title: "Ijazah Sekolah Dasar Misskey" + description: "Tutorial selesai" + _bubbleGameExplodingHead: + title: "🤯" + description: "Obyek paling terbesar di permainan gelembung" + _bubbleGameDoubleExplodingHead: + title: "Ganda 🤯" + description: "Dua dari obyek paling terbesar pada permainan gelembung di waktu yang sama" + flavor: "Kamu dapat mengisi kotak makan siang seperti ini 🤯 🤯." _role: new: "Buat peran" edit: "Sunting peran" @@ -1555,7 +1650,9 @@ _role: assignTarget: "Tipe tugas" descriptionOfAssignTarget: "Manual untuk mengganti secara manual siapa yang mendapatkan peran ini dan siapa yang tidak.\nKondisional untuk pengguna secara otomatis dimasukkan atau dihapus dari peran berdasarkan kondisi yang ditentukan." manual: "Manual" + manualRoles: "Peran manual" conditional: "Kondisional" + conditionalRoles: "Peran kondisional" condition: "Kondisi" isConditionalRole: "Ini adalah peran kondisional" isPublic: "Publikkan Peran" @@ -1583,6 +1680,7 @@ _role: gtlAvailable: "Dapat melihat lini masa global" ltlAvailable: "Dapat melihat lini masa lokal" canPublicNote: "Dapat mengirim catatan publik" + mentionMax: "Jumlah maksimum sebutan dalam sebuah catatan" canInvite: "Dapat membuat kode undangan instansi" inviteLimit: "Batas jumlah undangan" inviteLimitCycle: "Interval Penerbitan Kode Undangan" @@ -1604,9 +1702,16 @@ _role: canHideAds: "Dapat menyembunyikan iklan" canSearchNotes: "Penggunaan pencarian catatan" canUseTranslator: "Penggunaan penerjemah" + avatarDecorationLimit: "Jumlah maksimum dekorasi avatar yang dapat diterapkan" _condition: + roleAssignedTo: "Ditugaskan ke peran manual" isLocal: "Pengguna lokal" isRemote: "Pengguna remote" + isCat: "Pengguna Kucing" + isBot: "Pengguna Bot" + isSuspended: "Pengguna yang ditangguhkan" + isLocked: "Akun privat" + isExplorable: "Pengguna efektif yang akunnya dapat dicari" createdLessThan: "Telah berlalu kurang dari X sejak pembuatan akun" createdMoreThan: "Telah berlalu lebih dari X sejak pembuatan akun" followersLessThanOrEq: "Memiliki pengikut X atau kurang dari tersebut" @@ -1632,6 +1737,7 @@ _emailUnavailable: disposable: "Alamat surel temporer tidak dapat digunakan" mx: "Peladen alamat surel ini tidak valid" smtp: "Peladen alamat surel ini tidak merespon" + banned: "Kamu tidak dapat mendaftar dengan alamat surel ini" _ffVisibility: public: "Terbitkan" followers: "Tampil untuk pengikut saja" @@ -1675,6 +1781,7 @@ _plugin: installWarn: "Mohon jangan memasang plugin yang tidak dapat dipercayai." manage: "Manajemen plugin" viewSource: "Lihat sumber" + viewLog: "Tampilkan log" _preferencesBackups: list: "Cadangan yang dibuat" saveNew: "Simpan cadangan baru" @@ -1704,10 +1811,13 @@ _aboutMisskey: contributors: "Kontributor utama" allContributors: "Seluruh kontributor" source: "Sumber kode" + original: "Asli" + thisIsModifiedVersion: "{name} menggunakan versi modifikasi dari Misskey yang asli." translation: "Terjemahkan Misskey" donate: "Donasi ke Misskey" morePatrons: "Kami sangat mengapresiasi dukungan dari banyak penolong lain yang tidak tercantum disini. Terima kasih! 🥰" patrons: "Pendukung" + projectMembers: "Anggota proyek" _displayOfSensitiveMedia: respect: "Sembunyikan media yang ditandai sensitif" ignore: "Tampilkan media yang ditandai sensitif" @@ -1732,6 +1842,7 @@ _channel: notesCount: "terdapat {n} catatan" nameAndDescription: "Nama dan deskripsi" nameOnly: "Hanya nama" + allowRenoteToExternal: "Perbolehkan catat ulang dan kutipan di luar dari kanal" _menuDisplay: sideFull: "Horisontal" sideIcon: "Horisontal (Ikon)" @@ -1860,7 +1971,6 @@ _2fa: registerTOTP: "Daftarkan aplikasi autentikator" step1: "Pertama, pasang aplikasi autentikasi (seperti {a} atau {b}) di perangkat kamu." step2: "Lalu, pindai kode QR yang ada di layar." - step2Click: "Mengeklik kode QR ini akan membolehkanmu untuk mendaftarkan 2FA ke security-key atau aplikasi autentikator ponsel." step2Uri: "Masukkan URI berikut jika kamu menggunakan program desktop" step3Title: "Masukkan kode autentikasi" step3: "Masukkan token yang telah disediakan oleh aplikasimu untuk menyelesaikan pemasangan." @@ -1884,6 +1994,7 @@ _2fa: backupCodesDescription: "Kamu dapat menggunakan kode ini untuk mendapatkan akses ke akun kamu apabila berada dalam situasi tidak dapat menggunakan aplikasi autentikasi 2-faktor yang kamu miliki. Setiap kode hanya dapat digunakan satu kali. Mohon simpan kode ini di tempat yang aman." backupCodeUsedWarning: "Kode cadangan telah digunakan. Mohon mengatur ulang autentikasi 2-faktor secepatnya apabila kamu sudah tidak dapat menggunakannya lagi." backupCodesExhaustedWarning: "Semua kode cadangan telah digunakan. Apabila kamu kehilangan akses pada aplikasi autentikasi 2-faktor milikmu, kamu tidak dapat mengakses akun ini lagi. Mohon atur ulang autentikasi 2-faktor kamu." + moreDetailedGuideHere: "Berikut panduan detilnya" _permissions: "read:account": "Lihat informasi akun" "write:account": "Sunting informasi akun" @@ -1934,7 +2045,6 @@ _permissions: "read:admin:server-info": "Lihat informasi peladen" "read:admin:show-moderation-log": "Lihat log moderasi" "read:admin:show-user": "Lihat informasi pengguna privat" - "read:admin:show-users": "Lihat informasi pengguna privat" "write:admin:suspend-user": "Tangguhkan pengguna" "write:admin:unset-user-avatar": "Hapus avatar pengguna" "write:admin:unset-user-banner": "Hapus banner pengguna" @@ -2145,6 +2255,7 @@ _play: title: "Judul" script: "Script" summary: "Deskripsi" + visibilityDescription: "Membuat catatan ini privat berarti tidak akan terlihat pada profil kamu, namun siapapun yang memiliki URL dari catatan ini akan dapat mengaksesnya." _pages: newPage: "Buat halaman baru" editPage: "Sunting halaman" @@ -2189,6 +2300,8 @@ _pages: section: "Bagian" image: "Gambar" button: "Tombol" + dynamic: "Blok Dinamis" + dynamicDescription: "Blok ini telah dihapus. Mohon gunakan {play} dari sekarang." note: "Catatan yang ditanam" _note: id: "ID Catatan" @@ -2218,8 +2331,10 @@ _notification: sendTestNotification: "Kirim tes notifikasi" notificationWillBeDisplayedLikeThis: "Notifikasi akan terlihat seperti ini" reactedBySomeUsers: "{n} orang memberikan reaksi" + likedBySomeUsers: "{n} pengguna menyukai catatan kamu" renotedBySomeUsers: "{n} orang telah merenote" followedBySomeUsers: "{n} orang telah mengikuti" + flushNotification: "Bersihkan notifikasi" _types: all: "Semua" note: "Catatan baru" @@ -2317,6 +2432,7 @@ _moderationLogTypes: resetPassword: "Atur ulang kata sandi" suspendRemoteInstance: "Instansi luar telah ditangguhkan" unsuspendRemoteInstance: "Instansi luar batal ditangguhkan" + updateRemoteInstanceNote: "Catatan moderasi telah diperbaharui untuk peladen luar." markSensitiveDriveFile: "Berkas ditandai sensitif" unmarkSensitiveDriveFile: "Berkas batal ditandai sensitif" resolveAbuseReport: "Laporan terselesaikan" @@ -2428,4 +2544,35 @@ _reversi: isLlotheo: "Pemain dengan batu yang sedikit menang (Llotheo)" loopedMap: "Peta melingkar" canPutEverywhere: "Keping dapat ditaruh dimana saja" - + timeLimitForEachTurn: "Batas waktu untuk gantian" + freeMatch: "Pertandingan bebas" + lookingForPlayer: "Mencari lawan..." + gameCanceled: "Permainan ini telah dibatalkan." + shareToTlTheGameWhenStart: "Bagikan permainan ke lini masa ketika dimulai" + iStartedAGame: "Permainan telah dimulai! #MisskeyReversi" + opponentHasSettingsChanged: "Lawan telah mengganti pengaturan mereka." + allowIrregularRules: "Aturan non-reguler (bebas sepenuhnya)" + disallowIrregularRules: "Tanpa aturan non-reguler" + showBoardLabels: "Tampilkan penomoran baris dan kolom pada papan" + useAvatarAsStone: "Ubah batu menjadi avatar pengguna" +_offlineScreen: + title: "Luring - tidak dapat terhubung ke peladen" + header: "Tidak dapat tersambung ke server" +_urlPreviewSetting: + title: "Pengaturan pratinjau URL" + enable: "Aktifkan pratinjau URL" + timeout: "Waktu timeout pratinjau URL (ms)" + timeoutDescription: "Apabila ini memakan waktu lama dari nilai yang ditentukan untuk mendapatkan pratinjau, pratinjau tidak akan dibuat." + maximumContentLength: "Content-Length Maksimum (bytes)" + maximumContentLengthDescription: "Apabila Content-Length lebih besar dari nilai ini, pratinjau tidak akan dibuat." + requireContentLength: "Buat pratinjau hanya ketika Content-Length dapat didapatkan" + requireContentLengthDescription: "Apabila peladen lain tidak memberika Content-Length, pratinjau tidak akan dibuat." + userAgent: "User-Agent" + userAgentDescription: "Atur User-Agent yang digunakan untuk mengambil pratinjau. Apabila dibiarkan kosong, User-Agent bawaan akan digunakan." + summaryProxy: "Titik akhir proksi yang membuat pratinjau" + summaryProxyDescription: "Bukan untuk Misskey, namun untuk menghasilkan pratinjau menggunakan Summaly Proxy." + summaryProxyDescription2: "Parameter berikut tertautkan dengan proksi sebagai string kueri. Apabila proksi tidak mendukung tersebut, nilai di dalamnya diabaikan." +_mediaControls: + pip: "Gambar dalam Gambar" + playbackRate: "Kecepatan Pemutaran" + loop: "Ulangi Pemutaran" diff --git a/locales/index.d.ts b/locales/index.d.ts index 1d0607111f..e5f77cf239 100644 --- a/locales/index.d.ts +++ b/locales/index.d.ts @@ -456,6 +456,10 @@ export interface Locale extends ILocale { * ブーストしました。 */ "renoted": string; + /** + * {name} にブーストしました。 + */ + "renotedToX": ParameterizedString<"name">; /** * 引用。 */ @@ -484,6 +488,14 @@ export interface Locale extends ILocale { * チャンネル内引用 */ "inChannelQuote": string; + /** + * チャンネルにリノート + */ + "renoteToChannel": string; + /** + * 他のチャンネルにリノート + */ + "renoteToOtherChannel": string; /** * ピン留めされたノート */ @@ -945,7 +957,7 @@ export interface Locale extends ILocale { */ "silencedInstances": string; /** - * サイレンスしたいインスタンスのホストを改行で区切って設定します。サイレンスされたインスタンスに所属するアカウントはすべて「サイレンス」として扱われ、フォローがすべてリクエストになり、フォロワーでないローカルアカウントにはメンションできなくなります。ブロックしたインスタンスには影響しません。 + * サイレンスしたいサーバーのホストを改行で区切って設定します。サイレンスされたサーバーに所属するアカウントはすべて「サイレンス」として扱われ、フォローがすべてリクエストになります。ブロックしたインスタンスには影響しません。 */ "silencedInstancesDescription": string; /** @@ -1308,6 +1320,10 @@ export interface Locale extends ILocale { * フォルダーを選択 */ "selectFolders": string; + /** + * ファイルが選択されていません + */ + "fileNotSelected": string; /** * ファイル名を変更 */ @@ -1660,6 +1676,10 @@ export interface Locale extends ILocale { * 除外キーワード */ "antennaExcludeKeywords": string; + /** + * Botアカウントを除外 + */ + "antennaExcludeBots": string; /** * スペースで区切るとAND指定になり、改行で区切るとOR指定になります */ @@ -1936,6 +1956,10 @@ export interface Locale extends ILocale { * 引用として添付しますか? */ "quoteQuestion": string; + /** + * クリップボードのテキストが長いです。テキストファイルとして添付しますか? + */ + "attachAsFileQuestion": string; /** * まだチャットはありません */ @@ -2044,6 +2068,10 @@ export interface Locale extends ILocale { * ノートのアクションをホバー時のみ表示する */ "showNoteActionsOnlyHover": string; + /** + * ノートのリアクション数を表示する + */ + "showReactionsCount": string; /** * 履歴はありません */ @@ -3428,6 +3456,10 @@ export interface Locale extends ILocale { * 管理者情報が設定されていません。 */ "noMaintainerInformationWarning": string; + /** + * 問い合わせ先URLが設定されていません。 + */ + "noInquiryUrlWarning": string; /** * Botプロテクションが設定されていません。 */ @@ -4258,9 +4290,17 @@ export interface Locale extends ILocale { */ "thisPostIsMissingAltText": string; /** - * 見たことのあるブーストを省略して表示 + * ブーストのスマート省略 */ "collapseRenotes": string; + /** + * リアクションやブーストをしたことがあるノートをたたんで表示します。 + */ + "collapseRenotesDescription": string; + /** + * 返信されたノート省略 + */ + "collapseNotesRepliedTo": string; /** * ファイルを折りたたむ */ @@ -5125,6 +5165,78 @@ export interface Locale extends ILocale { * リトライ */ "gameRetry": string; + /** + * 使用しない場合は空欄にしてください + */ + "notUsePleaseLeaveBlank": string; + /** + * ワンタイムパスワードを使う + */ + "useTotp": string; + /** + * バックアップコードを使う + */ + "useBackupCode": string; + /** + * アプリを起動 + */ + "launchApp": string; + /** + * 動画・音声の再生にブラウザのUIを使用する + */ + "useNativeUIForVideoAudioPlayer": string; + /** + * オリジナルのファイル名を保持 + */ + "keepOriginalFilename": string; + /** + * この設定をオフにすると、アップロード時にファイル名が自動でランダム文字列に置き換えられます。 + */ + "keepOriginalFilenameDescription": string; + /** + * 説明文はありません + */ + "noDescription": string; + /** + * フォローの際常に確認する + */ + "alwaysConfirmFollow": string; + /** + * お問い合わせ + */ + "inquiry": string; + "_delivery": { + /** + * 配信状態 + */ + "status": string; + /** + * 配信停止 + */ + "stop": string; + /** + * 配信再開 + */ + "resume": string; + "_type": { + /** + * 配信中 + */ + "none": string; + /** + * 手動停止中 + */ + "manuallySuspended": string; + /** + * サーバー削除のため停止中 + */ + "goneSuspended": string; + /** + * サーバー応答なしのため停止中 + */ + "autoSuspendedForNotResponding": string; + }; + }; "_bubbleGame": { /** * 遊び方 @@ -5584,6 +5696,14 @@ export interface Locale extends ILocale { * 有効にすると、タイムラインがキャッシュされていない場合にDBへ追加で問い合わせを行うフォールバック処理を行います。無効にすると、フォールバック処理を行わないことでさらにサーバーの負荷を軽減することができますが、タイムラインが取得できる範囲に制限が生じます。 */ "fanoutTimelineDbFallbackDescription": string; + /** + * 問い合わせ先URL + */ + "inquiryUrl": string; + /** + * サーバー運営者へのお問い合わせフォームのURLや、運営者の連絡先等が記載されたWebページのURLを指定します。 + */ + "inquiryUrlDescription": string; }; "_accountMigration": { /** @@ -6773,6 +6893,26 @@ export interface Locale extends ILocale { * リモートユーザー */ "isRemote": string; + /** + * 猫ユーザー + */ + "isCat": string; + /** + * botユーザー + */ + "isBot": string; + /** + * サスペンド済みユーザー + */ + "isSuspended": string; + /** + * 鍵アカウントユーザー + */ + "isLocked": string; + /** + * 「アカウントを見つけやすくする」が有効なユーザー + */ + "isExplorable": string; /** * アカウント作成から~以内 */ @@ -7034,6 +7174,10 @@ export interface Locale extends ILocale { * ソースを表示 */ "viewSource": string; + /** + * ログを表示 + */ + "viewLog": string; }; "_preferencesBackups": { /** @@ -7767,13 +7911,9 @@ export interface Locale extends ILocale { */ "step1": ParameterizedString<"a" | "b">; /** - * 次に、表示されているQRコードをアプリでスキャンします。 + * 次に、表示されているQRコードをアプリでスキャンするか、ボタンをクリックして端末上でアプリを開きます。 */ "step2": string; - /** - * QRコードをクリックすると、お使いの端末にインストールされている認証アプリやキーリングに登録できます。 - */ - "step2Click": string; /** * デスクトップアプリを使用する場合は次のURIを入力します */ @@ -7866,6 +8006,10 @@ export interface Locale extends ILocale { * バックアップコードが全て使用されました。認証アプリを利用できない場合、これ以上アカウントにアクセスできなくなります。認証アプリを再登録してください。 */ "backupCodesExhaustedWarning": string; + /** + * 詳細なガイドはこちら + */ + "moreDetailedGuideHere": string; }; "_permissions": { /** @@ -8064,10 +8208,6 @@ export interface Locale extends ILocale { * ユーザーのプライベートな情報を見る */ "read:admin:show-user": string; - /** - * ユーザーのプライベートな情報を見る - */ - "read:admin:show-users": string; /** * ユーザーを凍結する */ @@ -8904,6 +9044,10 @@ export interface Locale extends ILocale { * 説明 */ "summary": string; + /** + * 非公開に設定するとプロフィールに表示されなくなりますが、URLを知っている人は引き続きアクセスできます。 + */ + "visibilityDescription": string; }; "_pages": { /** @@ -9075,6 +9219,14 @@ export interface Locale extends ILocale { * ボタン */ "button": string; + /** + * 動的ブロック + */ + "dynamic": string; + /** + * このブロックは廃止されています。今後は{play}を利用してください。 + */ + "dynamicDescription": ParameterizedString<"play">; /** * ノート埋め込み */ @@ -9191,7 +9343,11 @@ export interface Locale extends ILocale { */ "reactedBySomeUsers": ParameterizedString<"n">; /** - * {n}人がブーストしました + * {n}人がいいねしました + */ + "likedBySomeUsers": ParameterizedString<"n">; + /** + * {n}人がリノートしました */ "renotedBySomeUsers": ParameterizedString<"n">; /** @@ -9288,6 +9444,10 @@ export interface Locale extends ILocale { * カラムを追加 */ "addColumn": string; + /** + * 新着ノート通知の設定 + */ + "newNoteNotificationSettings": string; /** * カラムの設定 */ @@ -10071,6 +10231,74 @@ export interface Locale extends ILocale { */ "header": string; }; + "_urlPreviewSetting": { + /** + * URLプレビューの設定 + */ + "title": string; + /** + * URLプレビューを有効にする + */ + "enable": string; + /** + * プレビュー取得時のタイムアウト(ms) + */ + "timeout": string; + /** + * プレビュー取得の所要時間がこの値を超えた場合、プレビューは生成されません。 + */ + "timeoutDescription": string; + /** + * Content-Lengthの最大値(byte) + */ + "maximumContentLength": string; + /** + * Content-Lengthがこの値を超えた場合、プレビューは生成されません。 + */ + "maximumContentLengthDescription": string; + /** + * Content-Lengthが取得できた場合のみプレビューを生成 + */ + "requireContentLength": string; + /** + * 相手サーバがContent-Lengthを返さない場合、プレビューは生成されません。 + */ + "requireContentLengthDescription": string; + /** + * User-Agent + */ + "userAgent": string; + /** + * プレビュー取得時に使用されるUser-Agentを設定します。空欄の場合、デフォルトのUser-Agentが使用されます。 + */ + "userAgentDescription": string; + /** + * プレビューを生成するプロキシのエンドポイント + */ + "summaryProxy": string; + /** + * Misskey本体ではなく、サマリープロキシを使用してプレビューを生成します。 + */ + "summaryProxyDescription": string; + /** + * プロキシには下記パラメータがクエリ文字列として連携されます。プロキシ側がこれらをサポートしない場合、設定値は無視されます。 + */ + "summaryProxyDescription2": string; + }; + "_mediaControls": { + /** + * ピクチャインピクチャ + */ + "pip": string; + /** + * 再生速度 + */ + "playbackRate": string; + /** + * ループ再生 + */ + "loop": string; + }; } declare const locales: { [lang: string]: Locale; diff --git a/locales/it-IT.yml b/locales/it-IT.yml index 3868eea9e3..2b04c5abfb 100644 --- a/locales/it-IT.yml +++ b/locales/it-IT.yml @@ -86,7 +86,7 @@ note: "Nota" notes: "Note" following: "Follow" followers: "Follower" -followsYou: "Segue" +followsYou: "Follower" createList: "Aggiungi una nuova lista" manageLists: "Gestisci liste" error: "Errore" @@ -135,12 +135,12 @@ deleteFile: "File da Drive eliminato" markAsSensitive: "Segna come esplicito" unmarkAsSensitive: "Non segnare come esplicito " enterFileName: "Nome del file" -mute: "Silenzia" +mute: "Silenziare" unmute: "Riattiva l'audio" -renoteMute: "Silenzia le Rinota" +renoteMute: "Silenziare le Rinota" renoteUnmute: "Non silenziare le Rinota" -block: "Blocca" -unblock: "Sblocca" +block: "Bloccare" +unblock: "Sbloccare" suspend: "Sospensione" unsuspend: "Revoca la sospensione" blockConfirm: "Vuoi davvero bloccare il profilo?" @@ -201,8 +201,8 @@ charts: "Grafici" perHour: "orario" perDay: "giornaliero" stopActivityDelivery: "Interrompi la distribuzione di attività" -blockThisInstance: "Blocca questa istanza" -silenceThisInstance: "Silenzia l'istanza" +blockThisInstance: "Bloccare l'istanza" +silenceThisInstance: "Silenziare l'istanza" operations: "Operazioni" software: "Software" version: "Versione" @@ -224,7 +224,7 @@ blockedInstances: "Istanze bloccate" blockedInstancesDescription: "Elenca le istanze che vuoi bloccare, una per riga. Esse non potranno più interagire con la tua istanza." silencedInstances: "Istanze silenziate" silencedInstancesDescription: "Elenca i nomi host delle istanze che vuoi silenziare. Tutti i profili nelle istanze silenziate vengono trattati come tali. Possono solo inviare richieste di follow e menzionare soltanto i profili locali che seguono. Le istanze bloccate non sono interessate." -muteAndBlock: "Silenziati / Bloccati" +muteAndBlock: "Silenziare e bloccare" mutedUsers: "Profili silenziati" blockedUsers: "Profili bloccati" noUsers: "Non ci sono profili" @@ -401,6 +401,7 @@ name: "Nome" antennaSource: "Fonte dell'antenna" antennaKeywords: "Parole chiavi da ricevere" antennaExcludeKeywords: "Parole chiavi da escludere" +antennaExcludeBots: "Escludere i Bot" antennaKeywordsDescription: "Sparando con uno spazio indichi la condizione E (and). Separando con un a capo, indichi la condizione O (or)." notifyAntenna: "Invia notifiche delle nuove note" withFileAntenna: "Solo note con file in allegato" @@ -411,7 +412,7 @@ withReplies: "Includere le risposte" connectedTo: "Connessione ai seguenti profili:" notesAndReplies: "Note e risposte" withFiles: "Con allegati" -silence: "Silenzia" +silence: "Silenziare" silenceConfirm: "Vuoi davvero silenziare questo profilo?" unsilence: "Riattiva" unsilenceConfirm: "Vuoi davvero riattivare questo profilo?" @@ -451,7 +452,7 @@ share: "Condividi" notFound: "Non trovato" notFoundDescription: "Nessuna pagina corrisponde all'URL indicata." uploadFolder: "Destinazione caricamento predefinita" -markAsReadAllNotifications: "Segna tutte le notifiche come lette" +markAsReadAllNotifications: "Segnare tutte le notifiche come lette" markAsReadAllUnreadNotes: "Segna tutte le note come lette" markAsReadAllTalkMessages: "Segna tutte le chat come lette" help: "Guida" @@ -495,6 +496,7 @@ emojiStyle: "Stile emoji" native: "Nativo" disableDrawer: "Non mostrare il menù sul drawer" showNoteActionsOnlyHover: "Mostra le azioni delle Note solo al passaggio del mouse" +showReactionsCount: "Visualizza il numero di reazioni su una nota" noHistory: "Nessuna cronologia" signinHistory: "Storico degli accessi al profilo" enableAdvancedMfm: "Attiva MFM avanzati" @@ -578,7 +580,7 @@ scratchpadDescription: "Lo Scratchpad offre un ambiente per esperimenti di AiScr output: "Uscita" script: "Script" disablePagesScript: "Disabilita AiScript nelle pagine" -updateRemoteUser: "Aggiorna le informazioni dal profilo remoto" +updateRemoteUser: "Aggiorna dati dal profilo remoto" unsetUserAvatar: "Rimozione foto profilo" unsetUserAvatarConfirm: "Vuoi davvero rimuovere la foto profilo?" unsetUserBanner: "Rimuovi intestazione profilo" @@ -588,7 +590,7 @@ deleteAllFilesConfirm: "Vuoi davvero eliminare tutti i file?" removeAllFollowing: "Annulla tutti i follow" removeAllFollowingDescription: "Cancella tutti i follows del server {host}. Per favore, esegui se, ad esempio, l'istanza non esiste più." userSuspended: "L'utente è in sospensione" -userSilenced: "Profilo silente." +userSilenced: "Profilo silenziato" yourAccountSuspendedTitle: "Questo profilo è sospeso" yourAccountSuspendedDescription: "Questo profilo è stato sospeso a causa di una violazione del regolamento. Per informazioni, contattare l'amministrazione. Si prega di non creare un nuovo account." tokenRevoked: "Il token non è valido" @@ -658,7 +660,7 @@ wordMute: "Filtri parole" hardWordMute: "Filtro parole forte" regexpError: "errore regex" regexpErrorDescription: "Si è verificato un errore nell'espressione regolare alla riga {line} della parola muta {tab}:" -instanceMute: "Silenzia l'istanza" +instanceMute: "Silenziare l'istanza" userSaysSomething: "{name} ha parlato" makeActive: "Attiva" display: "Visualizza" @@ -683,14 +685,14 @@ fileIdOrUrl: "ID o URL del file" behavior: "Comportamento" sample: "Esempio" abuseReports: "Segnalazioni" -reportAbuse: "Segnala" -reportAbuseRenote: "Segnala la Rinota" -reportAbuseOf: "Segnala {name}" +reportAbuse: "Segnalare" +reportAbuseRenote: "Segnalare la Rinota" +reportAbuseOf: "Segnalare {name}" fillAbuseReportDescription: "Per favore, spiegaci il motivo della segnalazione. Se riguarda una Nota precisa, indica anche l'indirizzo URL." abuseReported: "La segnalazione è stata inviata. Grazie." reporter: "il corrispondente" -reporteeOrigin: "Origine del segnalato" -reporterOrigin: "Origine del segnalatore" +reporteeOrigin: "Segnalazione a" +reporterOrigin: "Segnalazione da" forwardReport: "Inoltro di un report a un'istanza remota." forwardReportIsAnonymous: "L'istanza remota non vedrà le tue informazioni, apparirai come profilo di sistema, anonimo." send: "Inviare" @@ -864,7 +866,7 @@ troubleshooting: "Risoluzione problemi" useBlurEffect: "Utilizza effetto sfocatura" learnMore: "Più dettagli" misskeyUpdated: "Misskey è stato aggiornato!" -whatIsNew: "Visualizza le informazioni sull'aggiornamento" +whatIsNew: "Informazioni sull'aggiornamento" translate: "Traduci" translatedFrom: "Traduzione da {x}" accountDeletionInProgress: "È in corso l'eliminazione del profilo" @@ -890,7 +892,7 @@ manageAccounts: "Gestisci i profili" makeReactionsPublic: "Pubblicare la lista delle reazioni." makeReactionsPublicDescription: "La lista delle reazioni che avete fatto è a disposizione di tutti." classic: "Classico" -muteThread: "Silenzia conversazione" +muteThread: "Silenziare conversazione" unmuteThread: "Riattiva la conversazione" followingVisibility: "Visibilità dei profili seguiti" followersVisibility: "Visibilità dei profili che ti seguono" @@ -972,11 +974,11 @@ shuffle: "Casuale" account: "Account" move: "Sposta" pushNotification: "Notifiche Push" -subscribePushNotification: "Attiva le notifiche push" -unsubscribePushNotification: "Disattiva le notifiche push" +subscribePushNotification: "Attivare le notifiche push" +unsubscribePushNotification: "Disattivare le notifiche push" pushNotificationAlreadySubscribed: "Le notifiche push sono già attivate" pushNotificationNotSupported: "Il client o il server non supporta le notifiche push" -sendPushNotificationReadMessage: "Elimina le notifiche push dopo la relativa lettura" +sendPushNotificationReadMessage: "Eliminare le notifiche push dopo la relativa lettura" sendPushNotificationReadMessageCaption: "Se possibile, verrà mostrata brevemente una notifica con il testo \"{emptyPushNotificationMessage}\". Potrebbe influire negativamente sulla durata della batteria." windowMaximize: "Ingrandisci" windowMinimize: "Contrai finestra" @@ -1164,6 +1166,7 @@ showRenotes: "Includi le Rinota" edited: "Modificato" notificationRecieveConfig: "Preferenze di notifica" mutualFollow: "Follow reciproco" +followingOrFollower: "Following o Follower" fileAttachedOnly: "Solo con allegati" showRepliesToOthersInTimeline: "Risposte altrui nella TL" hideRepliesToOthersInTimeline: "Nascondi Riposte altrui nella TL" @@ -1214,6 +1217,8 @@ soundWillBePlayed: "Con musica ed effetti sonori" showReplay: "Vedi i replay" replay: "Replay" replaying: "Replay in corso" +endReplay: "Termina replay" +copyReplayData: "Copia replay" ranking: "Classifica" lastNDays: "Ultimi {n} giorni" backToTitle: "Torna al titolo" @@ -1221,9 +1226,32 @@ hemisphere: "Geolocalizzazione" withSensitive: "Mostra le Note con allegati espliciti" userSaysSomethingSensitive: "Note da {name} con allegati espliciti" enableHorizontalSwipe: "Trascina per invertire i tab" +loading: "Caricamento" surrender: "Annulla" +gameRetry: "Riprova" +notUsePleaseLeaveBlank: "Lasciare vuoto, se non in uso" +useTotp: "Usare il codice OTP" +useBackupCode: "Usare il codice usa-e-getta" +launchApp: "Esegui l'App" +useNativeUIForVideoAudioPlayer: "Riprodurre audio/video usando le funzionalità del browser" +keepOriginalFilename: "Mantieni il nome file originale" +keepOriginalFilenameDescription: "Disattivandola, i file verranno caricati usando nomi casuali." +noDescription: "Manca la descrizione" +_delivery: + stop: "Sospensione" + _type: + none: "Pubblicazione" _bubbleGame: howToPlay: "Come giocare" + hold: "Tieni" + _score: + score: "Punteggio" + scoreYen: "Capitale" + highScore: "Punteggio migliore" + maxChain: "Miglior combo" + yen: "{yen}¥" + estimatedQty: "{qty} punti" + scoreSweets: "Onigiri {onigiriQtyWithUnit}" _howToPlay: section1: "Scegli la posizione e rilascia l'oggetto nel contenitore." section2: "Se due oggetti dello stesso tipo si toccano, si trasformano in un oggetto diverso, aumentando il punteggio." @@ -1239,7 +1267,7 @@ _announcement: readConfirmText: "Hai già letto \"{title}˝?" shouldNotBeUsedToPresentPermanentInfo: "Ti consigliamo di utilizzare gli annunci per pubblicare informazioni tempestive e limitate nel tempo, anziché informazioni importanti a lungo andare nel tempo, poiché potrebbero risultare difficili da ritrovare e peggiorare la fruibilità del servizio, specialmente alle nuove persone iscritte." dialogAnnouncementUxWarn: "Ti consigliamo di usarli con cautela, poiché è molto probabile che avere più di un annuncio in stile \"finestra di dialogo\" peggiori sensibilmente la fruibilità del servizio, specialmente alle nuove persone iscritte." - silence: "Silenzia gli annunci" + silence: "Silenziare gli annunci" silenceDescription: "Se attivi questa opzione, non riceverai notifiche sugli annunci, evitando di contrassegnarle come già lette." _initialAccountSetting: accountCreated: "Il tuo profilo è stato creato!" @@ -1278,14 +1306,14 @@ _initialTutorial: letsTryReacting: "Puoi aggiungere una Reazione cliccando il bottone \"{reaction}\" della relativa Nota. Prova ad aggiungerne una a questa Nota di esempio!" reactToContinue: "Aggiungere la Reazione ti consentirà di procedere col tutorial." reactNotification: "Quando qualcuno reagisce alle tue Note, ricevi una notifica in tempo reale." - reactDone: "Puoi annullare la tua Reazione premendo il bottone \"{undo}\"" + reactDone: "Annulla la tua Reazione premendo il bottone \"{undo}\"" _timeline: title: "Come funziona la Timeline" description1: "Misskey fornisce alcune Timeline (sequenze cronologiche di Note). Una di queste potrebbe essere stata disattivata dagli amministratori." - home: "Puoi vedere le Note provenienti dai profili che segui (follow)." - local: "Puoi vedere tutte le Note pubblicate dai profili di questa istanza." - social: "Puoi vedere sia le Note della Timeline Home che quelle della Timeline Locale, insieme!" - global: "Puoi vedere le Note da pubblicate da tutte le altre istanze federate con la nostra." + home: "le Note provenienti dai profili che segui (follow)." + local: "tutte le Note pubblicate dai profili di questa istanza." + social: "sia le Note della Timeline Home che quelle della Timeline Locale, insieme!" + global: "le Note da pubblicate da tutte le altre istanze federate con la nostra." description2: "Nella parte superiore dello schermo, puoi scegliere una Timeline o l'altra in qualsiasi momento." description3: "Ci sono anche sequenze temporali di elenchi, sequenze temporali di canali, ecc. Per ulteriori dettagli, consultare il {link}.\nPuoi vedere anche Timeline delle liste di profili (se ne hai create), canali, ecc... Per i dettagli, visita {link}." _postNote: @@ -1309,13 +1337,13 @@ _initialTutorial: useCases: "Utilizzalo per chiarire il contenuto della Nota, prima che sia letta. Come richiesto dal regolamento del server o per autoregolamentare spoiler e testi troppo espliciti." _howToMakeAttachmentsSensitive: title: "Come indicare che gli allegati sono espliciti?" - description: "Contrassegnare gli allegati come espliciti, va fatto quando è richiesto dal regolamento del server o quando gli allegati non devono essere immediatamente visibili." + description: "Si fa quando è richiesto dal regolamento del server o quando non devono essere visibili immediatamente." tryThisFile: "Prova a rendere esplicite le immagini allegate a questo modulo!" _exampleNote: - note: "Ho fatto un errore aprendo il coperchio del natto... (fagioli di soia fermentati, particolarmente appiccicosi)" - method: "Per indicare che un allegato è esplicito, tocca il file per aprirne il menu e scegliere la voce \"Segna come esplicito\"." - sensitiveSucceeded: "Quando alleghi file, assicurati di indicare se è materiale esplicito, in modo appropriato, in base al regolamento del tuo server." - doItToContinue: "Impostando l'immagine come esplicita, potrai procedere col tutorial." + note: "AAA! Ho rotto il coperchio del natto... (fagioli di soia fermentati)" + method: "Tocca il file, si aprirà il menu, scegli la voce \"Segna come esplicito\"" + sensitiveSucceeded: "Quando alleghi file, assicurati di indicare se è materiale esplicito in modo appropriato, decidi in base al regolamento dell'istanza." + doItToContinue: "Imposta l'immagine come esplicita per procedere col tutorial." _done: title: "Il tutorial è finito! 🎉" description: "Queste sono solamente alcune delle funzionalità principali di Misskey. Per ulteriori informazioni, {link}." @@ -1341,7 +1369,7 @@ _serverSettings: _accountMigration: moveFrom: "Migra un altro profilo dentro a questo" moveFromSub: "Crea un alias verso un altro profilo remoto" - moveFromLabel: "Profilo da cui migrare:" + moveFromLabel: "Profilo da cui migrare #{n}" moveFromDescription: "Se desideri spostare i profili follower da un altro profilo a questo, devi prima creare un alias qui. Assicurati averlo creato PRIMA di eseguire l'attività! Inserisci l'indirizzo del profilo mittente in questo modo: @persona@istanza.it" moveTo: "Migrare questo profilo verso un un altro" moveToLabel: "Profilo verso cui migrare" @@ -1645,6 +1673,7 @@ _role: gtlAvailable: "Disponibilità della Timeline Federata" ltlAvailable: "Disponibilità della Timeline Locale" canPublicNote: "Scrivere Note con Visibilità Pubblica" + mentionMax: "Numero massimo di menzioni in una nota" canInvite: "Generare codici di invito all'istanza" inviteLimit: "Limite di codici invito" inviteLimitCycle: "Intervallo di emissione del codice di invito" @@ -1668,6 +1697,7 @@ _role: canUseTranslator: "Tradurre le Note" avatarDecorationLimit: "Numero massimo di decorazioni foto profilo installabili" _condition: + roleAssignedTo: "Assegnato a ruoli manualmente" isLocal: "Profilo locale" isRemote: "Profilo remoto" createdLessThan: "Profilo creato da meno di N" @@ -1739,6 +1769,7 @@ _plugin: installWarn: "Si prega di installare soltanto estensioni che provengono da fonti affidabili." manage: "Gestisci estensioni" viewSource: "Visualizza sorgente" + viewLog: "Mostra log" _preferencesBackups: list: "Elenco di impostazioni salvate in precedenza" saveNew: "Nuovo salvataggio" @@ -1814,7 +1845,7 @@ _instanceMute: instanceMuteDescription: "Disattiva tutte le note, le note di rinvio (condivisione) dell'istanza configurata, comprese le risposte agli utenti dell'istanza." instanceMuteDescription2: "Impostazione separata da una nuova riga" title: "Nasconde le note dell'istanza configurata." - heading: "Istanze da silenziare." + heading: "Istanze da silenziare" _theme: explore: "Esplora temi" install: "Installa un tema" @@ -1929,7 +1960,6 @@ _2fa: registerTOTP: "Registra una App di autenticazione a due fattori (2FA/MFA)" step1: "Innanzitutto, installa sul dispositivo un'App di autenticazione come {a} o {b}." step2: "Quindi, tramite la App installata, scansiona questo codice QR." - step2Click: "Cliccando sul codice QR, puoi registrarlo con l'app di autenticazione o il portachiavi installato sul tuo dispositivo." step2Uri: "Inserisci il seguente URL se desideri utilizzare una App per PC" step3Title: "Inserisci il codice di verifica" step3: "Inserite il token visualizzato nell'app e il gioco è fatto." @@ -1953,6 +1983,7 @@ _2fa: backupCodesDescription: "Puoi usare questi codici usa-e-getta per ottenere l'accesso al tuo profilo in caso sia impossibile usare l'App col codice OTP. Salvali in un posto sicuro." backupCodeUsedWarning: "È stato usato un codice usa-e-getta. Per favore, riconfigura l'autenticazione a due fattori il prima possibile, nel caso la configurazione precedente abbia smesso di funzionare." backupCodesExhaustedWarning: "Hai esaurito i codici usa-e-getta. Se l'App che genera il codice OTP non è più disponibile, non potrai più accedere al tuo profilo. Ripeti la configurazione per l'autenticazione a due fattori." + moreDetailedGuideHere: "Informazioni dettagliate sull'autenticazione multi fattore (2FA/MFA)" _permissions: "read:account": "Visualizza le informazioni sul profilo" "write:account": "Modifica le informazioni sul profilo" @@ -1969,8 +2000,8 @@ _permissions: "read:mutes": "Vedi i profili silenziati" "write:mutes": "Gestisci i profili silenziati" "write:notes": "Creare / Eliminare note" - "read:notifications": "Visualizza notifiche" - "write:notifications": "Gerisci notifiche" + "read:notifications": "Visualizzare notifiche" + "write:notifications": "Gestire notifiche" "read:reactions": "Vedi reazioni" "write:reactions": "Gerisci reazioni" "write:votes": "Votare" @@ -2003,7 +2034,6 @@ _permissions: "read:admin:server-info": "Vedere le informazioni sul server" "read:admin:show-moderation-log": "Vedere lo storico di moderazione" "read:admin:show-user": "Vedere le informazioni private degli account utente" - "read:admin:show-users": "Vedere le informazioni private degli account utente" "write:admin:suspend-user": "Sospendere i profili" "write:admin:unset-user-avatar": "Rimuovere la foto profilo dai profili" "write:admin:unset-user-banner": "Rimuovere l'immagine testata dai profili" @@ -2214,6 +2244,7 @@ _play: title: "Titolo" script: "Script" summary: "Descrizione" + visibilityDescription: "Impostarlo su privato significa che non verrà visualizzato sul tuo profilo, ma chiunque ha l'URL potrà comunque accedervi." _pages: newPage: "Crea pagina" editPage: "Modifica pagina" @@ -2258,6 +2289,8 @@ _pages: section: "Sezione" image: "Immagini" button: "Pulsante" + dynamic: "Riquadri dinamici" + dynamicDescription: "Questo riquadro è obsoleto. Utilizza {play} da ora in poi." note: "Nota integrata" _note: id: "ID nota" @@ -2282,13 +2315,15 @@ _notification: roleAssigned: "Ruolo assegnato" emptyPushNotificationMessage: "Le notifiche push sono state aggiornate." achievementEarned: "Obiettivo raggiunto" - testNotification: "Prova la notifica" - checkNotificationBehavior: "Prova il comportamento della notifica" + testNotification: "Provare la notifica" + checkNotificationBehavior: "Provare il comportamento della notifica" sendTestNotification: "Spedisci una notifica di prova" notificationWillBeDisplayedLikeThis: "La notifica apparirà così" reactedBySomeUsers: "{n} reazioni" + likedBySomeUsers: "{n} apprezzamenti" renotedBySomeUsers: "{n} Rinota" - followedBySomeUsers: "{n} nuovi follower" + followedBySomeUsers: "{n} follower" + flushNotification: "Azzera le notifiche" _types: all: "Tutto" note: "Nuove Note" @@ -2340,8 +2375,8 @@ _deck: direct: "Note Dirette" roleTimeline: "Timeline Ruolo" _dialog: - charactersExceeded: "Hai superato il limite di {max} caratteri! ({corrente})" - charactersBelow: "Sei al di sotto del minimo di {min} caratteri! ({corrente})" + charactersExceeded: "Hai superato il limite di {max} caratteri! ({current})" + charactersBelow: "Sei al di sotto del minimo di {min} caratteri! ({current})" _disabledTimeline: title: "Timeline disabilitata" description: "Il ruolo in cui sei non ti permette di leggere questa timeline" @@ -2386,6 +2421,7 @@ _moderationLogTypes: resetPassword: "Password azzerata" suspendRemoteInstance: "Istanza remota sospesa" unsuspendRemoteInstance: "Istanza remota riattivata" + updateRemoteInstanceNote: "Aggiornamento del promemoria di moderazione per il server remoto" markSensitiveDriveFile: "File nel Drive segnato come esplicito" unmarkSensitiveDriveFile: "File nel Drive segnato come non esplicito" resolveAbuseReport: "Segnalazione risolta" @@ -2506,6 +2542,24 @@ _reversi: opponentHasSettingsChanged: "L'avversario ha cambiato configurazione" allowIrregularRules: "Regole inconsuete (completamente libere)" disallowIrregularRules: "Impedire le regole inconsuete" + showBoardLabels: "Mostra le coordinate del gioco" + useAvatarAsStone: "Immagini profilo come pedine" _offlineScreen: title: "Scollegato. Impossibile connettersi al server" header: "Impossibile connettersi al server" +_urlPreviewSetting: + title: "Impostazioni per l'anteprima delle URL" + enable: "Attiva l'anteprima delle URL" + timeout: "Timeout dell'anteprima in millisecondi" + timeoutDescription: "Impegna al massimo il tempo indicato, altrimenti ignora l'anteprima" + maximumContentLength: "Grandezza del contenuto (Content-Length in byte)" + maximumContentLengthDescription: "Se la grandezza supera il valore, l'anteprima verrà ignorata." + requireContentLength: "Genenerare l'anteprima solo quando è definito Content-Length" + requireContentLengthDescription: "In assenza di questo parametro dal server remoto, l'anteprima verrà ignorata." + userAgent: "User-Agent" + userAgentDescription: "Definire con quale User-Agent si intende identificarsi durante l'acquisizione di un'anteprima. Se è vuoto, useremo il valore predefinito." + summaryProxy: "Endpoint proxy che genera l'anteprima" +_mediaControls: + pip: "Sovraimpressione" + playbackRate: "Velocità di riproduzione" + loop: "Ripetizione infinita" diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index d3911819a1..454e0b3cee 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -110,6 +110,7 @@ enterEmoji: "絵文字を入力" renote: "ブースト" unrenote: "ブースト解除" renoted: "ブーストしました。" +renotedToX: "{name} にブーストしました。" quoted: "引用。" rmboost: "ブースト解除しました。" cantRenote: "この投稿はブーストできません。" @@ -117,6 +118,8 @@ cantReRenote: "ブーストをブーストすることはできません。" quote: "引用" inChannelRenote: "チャンネル内ブースト" inChannelQuote: "チャンネル内引用" +renoteToChannel: "チャンネルにリノート" +renoteToOtherChannel: "他のチャンネルにリノート" pinnedNote: "ピン留めされたノート" pinned: "ピン留め" you: "あなた" @@ -232,7 +235,7 @@ clearCachedFilesConfirm: "キャッシュされたリモートファイルをす blockedInstances: "ブロックしたサーバー" blockedInstancesDescription: "ブロックしたいサーバーのホストを改行で区切って設定します。ブロックされたサーバーは、このインスタンスとやり取りできなくなります。" silencedInstances: "サイレンスしたサーバー" -silencedInstancesDescription: "サイレンスしたいインスタンスのホストを改行で区切って設定します。サイレンスされたインスタンスに所属するアカウントはすべて「サイレンス」として扱われ、フォローがすべてリクエストになり、フォロワーでないローカルアカウントにはメンションできなくなります。ブロックしたインスタンスには影響しません。" +silencedInstancesDescription: "サイレンスしたいサーバーのホストを改行で区切って設定します。サイレンスされたサーバーに所属するアカウントはすべて「サイレンス」として扱われ、フォローがすべてリクエストになります。ブロックしたインスタンスには影響しません。" muteAndBlock: "ミュートとブロック" mutedUsers: "ミュートしたユーザー" blockedUsers: "ブロックしたユーザー" @@ -323,6 +326,7 @@ selectFile: "ファイルを選択" selectFiles: "ファイルを選択" selectFolder: "フォルダーを選択" selectFolders: "フォルダーを選択" +fileNotSelected: "ファイルが選択されていません" renameFile: "ファイル名を変更" folderName: "フォルダー名" createFolder: "フォルダーを作成" @@ -411,6 +415,7 @@ name: "名前" antennaSource: "受信ソース" antennaKeywords: "受信キーワード" antennaExcludeKeywords: "除外キーワード" +antennaExcludeBots: "Botアカウントを除外" antennaKeywordsDescription: "スペースで区切るとAND指定になり、改行で区切るとOR指定になります" notifyAntenna: "新しいノートを通知する" withFileAntenna: "ファイルが添付されたノートのみ" @@ -480,6 +485,7 @@ expandAllCws: "すべての返信の内容を表示する" collapseAllCws: "すべての返信の内容を隠す" quoteAttached: "引用付き" quoteQuestion: "引用として添付しますか?" +attachAsFileQuestion: "クリップボードのテキストが長いです。テキストファイルとして添付しますか?" noMessagesYet: "まだチャットはありません" newMessageExists: "新しいメッセージがあります" onlyOneFileCanBeAttached: "メッセージに添付できるファイルはひとつです" @@ -507,6 +513,7 @@ emojiStyle: "絵文字のスタイル" native: "ネイティブ" disableDrawer: "メニューをドロワーで表示しない" showNoteActionsOnlyHover: "ノートのアクションをホバー時のみ表示する" +showReactionsCount: "ノートのリアクション数を表示する" noHistory: "履歴はありません" signinHistory: "ログイン履歴" enableAdvancedMfm: "高度なMFMを有効にする" @@ -853,6 +860,7 @@ administration: "管理" accounts: "アカウント" switch: "切り替え" noMaintainerInformationWarning: "管理者情報が設定されていません。" +noInquiryUrlWarning: "問い合わせ先URLが設定されていません。" noBotProtectionWarning: "Botプロテクションが設定されていません。" configure: "設定する" postToGallery: "ギャラリーへ投稿" @@ -1060,7 +1068,9 @@ thisPostMayBeAnnoyingIgnore: "このまま投稿" thisPostIsMissingAltTextCancel: "やめる" thisPostIsMissingAltTextIgnore: "このまま投稿" thisPostIsMissingAltText: "この投稿に添付されたファイルの 1 つに代替テキストがありません。すべての添付ファイルに代替テキストが含まれていることを確認してください。" -collapseRenotes: "見たことのあるブーストを省略して表示" +collapseRenotes: "ブーストのスマート省略" +collapseRenotesDescription: "リアクションやブーストをしたことがあるノートをたたんで表示します。" +collapseNotesRepliedTo: "返信されたノート省略" collapseFiles: "ファイルを折りたたむ" autoloadConversation: "返信に会話を読み込む" internalServerError: "サーバー内部エラー" @@ -1277,6 +1287,26 @@ enableHorizontalSwipe: "スワイプしてタブを切り替える" loading: "読み込み中" surrender: "やめる" gameRetry: "リトライ" +notUsePleaseLeaveBlank: "使用しない場合は空欄にしてください" +useTotp: "ワンタイムパスワードを使う" +useBackupCode: "バックアップコードを使う" +launchApp: "アプリを起動" +useNativeUIForVideoAudioPlayer: "動画・音声の再生にブラウザのUIを使用する" +keepOriginalFilename: "オリジナルのファイル名を保持" +keepOriginalFilenameDescription: "この設定をオフにすると、アップロード時にファイル名が自動でランダム文字列に置き換えられます。" +noDescription: "説明文はありません" +alwaysConfirmFollow: "フォローの際常に確認する" +inquiry: "お問い合わせ" + +_delivery: + status: "配信状態" + stop: "配信停止" + resume: "配信再開" + _type: + none: "配信中" + manuallySuspended: "手動停止中" + goneSuspended: "サーバー削除のため停止中" + autoSuspendedForNotResponding: "サーバー応答なしのため停止中" _bubbleGame: howToPlay: "遊び方" @@ -1409,6 +1439,8 @@ _serverSettings: fanoutTimelineDescription: "有効にすると、各種タイムラインを取得する際のパフォーマンスが大幅に向上し、データベースへの負荷を軽減することが可能です。ただし、Redisのメモリ使用量は増加します。サーバーのメモリ容量が少ない場合、または動作が不安定な場合は無効にすることができます。" fanoutTimelineDbFallback: "データベースへのフォールバック" fanoutTimelineDbFallbackDescription: "有効にすると、タイムラインがキャッシュされていない場合にDBへ追加で問い合わせを行うフォールバック処理を行います。無効にすると、フォールバック処理を行わないことでさらにサーバーの負荷を軽減することができますが、タイムラインが取得できる範囲に制限が生じます。" + inquiryUrl: "問い合わせ先URL" + inquiryUrlDescription: "サーバー運営者へのお問い合わせフォームのURLや、運営者の連絡先等が記載されたWebページのURLを指定します。" _accountMigration: moveFrom: "別のアカウントからこのアカウントに移行" @@ -1748,6 +1780,11 @@ _role: roleAssignedTo: "マニュアルロールにアサイン済み" isLocal: "ローカルユーザー" isRemote: "リモートユーザー" + isCat: "猫ユーザー" + isBot: "botユーザー" + isSuspended: "サスペンド済みユーザー" + isLocked: "鍵アカウントユーザー" + isExplorable: "「アカウントを見つけやすくする」が有効なユーザー" createdLessThan: "アカウント作成から~以内" createdMoreThan: "アカウント作成から~経過" followersLessThanOrEq: "フォロワー数が~以下" @@ -1829,6 +1866,7 @@ _plugin: installWarn: "信頼できないプラグインはインストールしないでください。" manage: "プラグインの管理" viewSource: "ソースを表示" + viewLog: "ログを表示" _preferencesBackups: list: "作成したバックアップ" @@ -2039,8 +2077,7 @@ _2fa: alreadyRegistered: "既に設定は完了しています。" registerTOTP: "認証アプリの設定を開始" step1: "まず、{a}や{b}などの認証アプリをお使いのデバイスにインストールします。" - step2: "次に、表示されているQRコードをアプリでスキャンします。" - step2Click: "QRコードをクリックすると、お使いの端末にインストールされている認証アプリやキーリングに登録できます。" + step2: "次に、表示されているQRコードをアプリでスキャンするか、ボタンをクリックして端末上でアプリを開きます。" step2Uri: "デスクトップアプリを使用する場合は次のURIを入力します" step3Title: "確認コードを入力" step3: "アプリに表示されている確認コード(トークン)を入力します。" @@ -2064,6 +2101,7 @@ _2fa: backupCodesDescription: "認証アプリが使用できなくなった場合、以下のバックアップコードを使ってアカウントにアクセスできます。これらのコードは必ず安全な場所に保管してください。各コードは一回だけ使用できます。" backupCodeUsedWarning: "バックアップコードが使用されました。認証アプリが使えなくなっている場合、なるべく早く認証アプリを再設定してください。" backupCodesExhaustedWarning: "バックアップコードが全て使用されました。認証アプリを利用できない場合、これ以上アカウントにアクセスできなくなります。認証アプリを再登録してください。" + moreDetailedGuideHere: "詳細なガイドはこちら" _permissions: "read:account": "アカウントの情報を見る" @@ -2115,7 +2153,6 @@ _permissions: "read:admin:server-info": "サーバーの情報を見る" "read:admin:show-moderation-log": "モデレーションログを見る" "read:admin:show-user": "ユーザーのプライベートな情報を見る" - "read:admin:show-users": "ユーザーのプライベートな情報を見る" "write:admin:suspend-user": "ユーザーを凍結する" "write:admin:unset-user-avatar": "ユーザーのアバターを削除する" "write:admin:unset-user-banner": "ユーザーのバーナーを削除する" @@ -2347,6 +2384,7 @@ _play: title: "タイトル" script: "スクリプト" summary: "説明" + visibilityDescription: "非公開に設定するとプロフィールに表示されなくなりますが、URLを知っている人は引き続きアクセスできます。" _pages: newPage: "ページの作成" @@ -2392,6 +2430,8 @@ _pages: section: "セクション" image: "画像" button: "ボタン" + dynamic: "動的ブロック" + dynamicDescription: "このブロックは廃止されています。今後は{play}を利用してください。" note: "ノート埋め込み" _note: @@ -2425,7 +2465,8 @@ _notification: sendTestNotification: "テスト通知を送信する" notificationWillBeDisplayedLikeThis: "通知はこのように表示されます" reactedBySomeUsers: "{n}人がリアクションしました" - renotedBySomeUsers: "{n}人がブーストしました" + likedBySomeUsers: "{n}人がいいねしました" + renotedBySomeUsers: "{n}人がリノートしました" followedBySomeUsers: "{n}人にフォローされました" flushNotification: "通知の履歴をリセットする" @@ -2454,6 +2495,7 @@ _deck: alwaysShowMainColumn: "常にメインカラムを表示" columnAlign: "カラムの寄せ" addColumn: "カラムを追加" + newNoteNotificationSettings: "新着ノート通知の設定" configureColumn: "カラムの設定" swapLeft: "左に移動" swapRight: "右に移動" @@ -2680,3 +2722,23 @@ _reversi: _offlineScreen: title: "オフライン - サーバーに接続できません" header: "サーバーに接続できません" + +_urlPreviewSetting: + title: "URLプレビューの設定" + enable: "URLプレビューを有効にする" + timeout: "プレビュー取得時のタイムアウト(ms)" + timeoutDescription: "プレビュー取得の所要時間がこの値を超えた場合、プレビューは生成されません。" + maximumContentLength: "Content-Lengthの最大値(byte)" + maximumContentLengthDescription: "Content-Lengthがこの値を超えた場合、プレビューは生成されません。" + requireContentLength: "Content-Lengthが取得できた場合のみプレビューを生成" + requireContentLengthDescription: "相手サーバがContent-Lengthを返さない場合、プレビューは生成されません。" + userAgent: "User-Agent" + userAgentDescription: "プレビュー取得時に使用されるUser-Agentを設定します。空欄の場合、デフォルトのUser-Agentが使用されます。" + summaryProxy: "プレビューを生成するプロキシのエンドポイント" + summaryProxyDescription: "Misskey本体ではなく、サマリープロキシを使用してプレビューを生成します。" + summaryProxyDescription2: "プロキシには下記パラメータがクエリ文字列として連携されます。プロキシ側がこれらをサポートしない場合、設定値は無視されます。" + +_mediaControls: + pip: "ピクチャインピクチャ" + playbackRate: "再生速度" + loop: "ループ再生" diff --git a/locales/ja-KS.yml b/locales/ja-KS.yml index edae188bb6..641425aa17 100644 --- a/locales/ja-KS.yml +++ b/locales/ja-KS.yml @@ -402,6 +402,7 @@ name: "名前" antennaSource: "受信ソース(このソースは食われへん)" antennaKeywords: "受信キーワード" antennaExcludeKeywords: "除外キーワード" +antennaExcludeBots: "Botアカウントを除外" antennaKeywordsDescription: "スペースで区切ったるとAND指定で、改行で区切ったるとOR指定や" notifyAntenna: "新しいノートを通知すんで" withFileAntenna: "なんか添付されたノートだけ" @@ -496,6 +497,7 @@ emojiStyle: "絵文字のスタイル" native: "ネイティブ" disableDrawer: "メニューをドロワーで表示せえへん" showNoteActionsOnlyHover: "ノートの操作部をホバー時のみ表示するで" +showReactionsCount: "ノートのリアクション数を表示する" noHistory: "履歴はないわ。" signinHistory: "ログイン履歴" enableAdvancedMfm: "ややこしいMFMもありにする" @@ -1044,6 +1046,8 @@ resetPasswordConfirm: "パスワード作り直すんでええな?" sensitiveWords: "けったいな単語" sensitiveWordsDescription: "設定した単語が入っとるノートの公開範囲をホームにしたるわ。改行で区切ったら複数設定できるで。" sensitiveWordsDescription2: "スペースで区切るとAND指定、キーワードをスラッシュで囲んだら正規表現や。" +prohibitedWords: "禁止ワード" +prohibitedWordsDescription: "設定した言葉が含まれるノートを投稿しようとしたら、エラーが出るようにするで。改行で区切って複数設定できるで。" prohibitedWordsDescription2: "スペースで区切るとAND指定、キーワードをスラッシュで囲んだら正規表現や。" hiddenTags: "見えてへんハッシュタグ" hiddenTagsDescription: "設定したタグを最近流行りのとこに見えんようにすんで。複数設定するときは改行で区切ってな。" @@ -1160,6 +1164,7 @@ showRenotes: "ブースト出す" edited: "いじったやつ" notificationRecieveConfig: "通知もらうかの設定" mutualFollow: "お互いフォローしてんで" +followingOrFollower: "フォロー中またはフォロワー" fileAttachedOnly: "ファイルのっけてあるやつだけ" showRepliesToOthersInTimeline: "タイムラインに他の人への返信とかも入れるで" hideRepliesToOthersInTimeline: "タイムラインに他の人への返信とかは入れへん" @@ -1169,6 +1174,12 @@ confirmShowRepliesAll: "これは元に戻せへんから慎重に決めてや confirmHideRepliesAll: "これは元に戻せへんから慎重に決めてや。本当にタイムラインに今フォローしとる全員の返信を入れへんのか?" externalServices: "他のサイトのサービス" sourceCode: "ソースコード" +sourceCodeIsNotYetProvided: "ソースコードはまだ提供されてへんで。問題の修正について管理者に問い合わせてみ。" +repositoryUrl: "リポジトリURL" +repositoryUrlDescription: "ソースコードが公開されているリポジトリがある場合、そのURLを記入するで。Misskeyをそのまんま(ソースコードにいかなる変更も加えずに)使っとる場合は https://github.com/misskey-dev/misskey と記入するで。" +repositoryUrlOrTarballRequired: "リポジトリを公開してへんなら、代わりにtarballを提供する必要があるで。詳細は.config/example.ymlを参照してな。" +feedback: "フィードバック" +feedbackUrl: "フィードバックURL" impressum: "運営者の情報" impressumUrl: "運営者の情報URL" impressumDescription: "ドイツとかの一部んところではな、表示が義務付けられてんねん(Impressum)。" @@ -1204,6 +1215,8 @@ soundWillBePlayed: "サウンドが再生されるで" showReplay: "リプレイ見る" replay: "リプレイ" replaying: "リプレイ中" +endReplay: "リプレイを終了" +copyReplayData: "リプレイデータをコピー" ranking: "ランキング" lastNDays: "直近{n}日" backToTitle: "タイトルへ" @@ -1211,9 +1224,34 @@ hemisphere: "住んでる地域" withSensitive: "センシティブなファイルを含むノートを表示" userSaysSomethingSensitive: "{name}のセンシティブなファイルを含む投稿" enableHorizontalSwipe: "スワイプしてタブを切り替える" +loading: "読み込み中" surrender: "やめとく" +gameRetry: "もういっちょ" +notUsePleaseLeaveBlank: "使用せえへん場合は空欄にしてや" +useTotp: "ワンタイムパスワードを使う" +useBackupCode: "バックアップコードを使う" +launchApp: "アプリを起動" +useNativeUIForVideoAudioPlayer: "動画・音声の再生にブラウザのUIを使用する" +keepOriginalFilename: "オリジナルのファイル名を保持" +keepOriginalFilenameDescription: "この設定をオフにすると、アップロード時にファイル名が自動でランダム文字列に置き換えられるで。" +noDescription: "説明文はあらへんで" +alwaysConfirmFollow: "フォローの際常に確認する" +inquiry: "問い合わせ" +_delivery: + stop: "配信せぇへん" + _type: + none: "配信しとる" _bubbleGame: howToPlay: "遊び方" + hold: "ホールド" + _score: + score: "スコア" + scoreYen: "稼いだ金額" + highScore: "ハイスコア" + maxChain: "最大チェーン数" + yen: "{yen}円" + estimatedQty: "{qty}個分" + scoreSweets: "おにぎり {onigiriQtyWithUnit}" _howToPlay: section1: "位置を調整してハコにモノを落とすで。" section2: "同じもんがくっついたら別のやつになって、スコアがもらえるで。" @@ -1635,6 +1673,7 @@ _role: gtlAvailable: "グローバルタイムライン見る" ltlAvailable: "ローカルタイムライン見る" canPublicNote: "パブリック投稿できるか" + mentionMax: "ノート内の最大メンション数" canInvite: "サーバー招待コード作る" inviteLimit: "招待コード作れる数" inviteLimitCycle: "招待コードの作れる間隔" @@ -1658,8 +1697,14 @@ _role: canUseTranslator: "翻訳使えるかどうか" avatarDecorationLimit: "アイコンデコのいっちばんつけれる数" _condition: + roleAssignedTo: "マニュアルロールにアサイン済み" isLocal: "ローカルユーザー" isRemote: "リモートユーザー" + isCat: "猫ユーザー" + isBot: "botユーザー" + isSuspended: "サスペンド済みユーザー" + isLocked: "鍵アカウントユーザー" + isExplorable: "「アカウントを見つけやすくする」が有効なユーザー" createdLessThan: "アカウント作ってから~以内" createdMoreThan: "アカウント作ってから~経過" followersLessThanOrEq: "フォロワー数が~以下" @@ -1729,6 +1774,7 @@ _plugin: installWarn: "信頼できへんプラグインはインストールせんとってな" manage: "プラグインの管理" viewSource: "ソース見る" + viewLog: "ログを表示" _preferencesBackups: list: "作ったバックアップ" saveNew: "新しく保存" @@ -1743,8 +1789,8 @@ _preferencesBackups: deleteConfirm: "{name}を消すん?" renameConfirm: "「{old}」を「{new}」に変えるん?" noBackups: "バックアップはないで。「新しく保存」ってとこでこのクライアント設定を鯖に保存できるで。" - createdAt: "作った日時:{date}{time}" - updatedAt: "更新日時:{date}{time}" + createdAt: "作った日時: {date} {time}" + updatedAt: "更新日時: {date} {time}" cannotLoad: "読み込みできへん..." invalidFile: "ファイル形式が違うで?" _registry: @@ -1758,6 +1804,8 @@ _aboutMisskey: contributors: "主な貢献者" allContributors: "全ての貢献者" source: "ソースコード" + original: "オリジナル" + thisIsModifiedVersion: "{name}はオリジナルのSharkeyをいじったバージョンをつこうてるで。" translation: "Sharkeyを翻訳" donate: "Sharkeyに寄付" morePatrons: "他にもぎょうさんの人からサポートしてもろてんねん。ほんまおおきに🥰" @@ -1916,7 +1964,6 @@ _2fa: registerTOTP: "認証アプリの設定はじめる" step1: "ほんなら、{a}や{b}とかの認証アプリを使っとるデバイスにインストールしてな。" step2: "次に、ここにあるQRコードをアプリでスキャンしてな~。" - step2Click: "QRコード押したら、今使とる端末に入っとる認証アプリとかキーリングに登録できるで。" step2Uri: "デスクトップアプリを使う時は次のURIを入れるで" step3Title: "確認コードを入れてーや" step3: "アプリに映っとる確認コード(トークン)を入れて終わりや。" @@ -1940,6 +1987,7 @@ _2fa: backupCodesDescription: "認証アプリが使用できんなった場合、以下のバックアップコードを使ってアカウントにアクセスできるで。これらのコードは必ず安全な場所に置いときや。各コードは一回だけ使用できるで。" backupCodeUsedWarning: "バックアップコードが使用されたで。認証アプリが使えなくなってるん場合、なるべく早く認証アプリを再設定しや。" backupCodesExhaustedWarning: "バックアップコードが全て使用されたで。認証アプリを利用できん場合、これ以上アカウントにアクセスできなくなるで。認証アプリを再登録しや。" + moreDetailedGuideHere: "詳細なガイドはこちら" _permissions: "read:account": "アカウントの情報を見るで" "write:account": "アカウントの情報を変更するで" @@ -1990,7 +2038,6 @@ _permissions: "read:admin:server-info": "サーバーの情報見る" "read:admin:show-moderation-log": "モデレーションログ見る" "read:admin:show-user": "ユーザーのプライベートな情報見る" - "read:admin:show-users": "ユーザーのプライベートな情報見る" "write:admin:suspend-user": "ユーザーを凍結" "write:admin:unset-user-avatar": "ユーザーのアバターを削除" "write:admin:unset-user-banner": "ユーザーのバナーを削除" @@ -2201,6 +2248,7 @@ _play: title: "タイトル" script: "スクリプト" summary: "説明" + visibilityDescription: "非公開に設定するとプロフィールに表示されへんくなるけど、URLを知っとる人は引き続きアクセスできるで。" _pages: newPage: "ページを作る" editPage: "ページの編集" @@ -2245,6 +2293,8 @@ _pages: section: "セクション" image: "画像" button: "ボタン" + dynamic: "動的ブロック" + dynamicDescription: "このブロックは廃止されとるで。今後は{play}を利用してや。" note: "ノート埋め込み" _note: id: "ノートID" @@ -2274,8 +2324,10 @@ _notification: sendTestNotification: "テスト通知を送信するで" notificationWillBeDisplayedLikeThis: "通知はこのように表示されるで" reactedBySomeUsers: "{n}人がツッコんだで" + likedBySomeUsers: "{n}人がいいねしたで" renotedBySomeUsers: "{n}人がブーストしたで" followedBySomeUsers: "{n}人にフォローされたで" + flushNotification: "通知の履歴をリセットする" _types: all: "すべて" note: "あんたらの新規投稿" @@ -2373,6 +2425,7 @@ _moderationLogTypes: resetPassword: "パスワードをリセット" suspendRemoteInstance: "リモートサーバーを止めんで" unsuspendRemoteInstance: "リモートサーバーを再開すんで" + updateRemoteInstanceNote: "リモートサーバーのモデレーションノート更新" markSensitiveDriveFile: "ファイルをセンシティブ付与" unmarkSensitiveDriveFile: "ファイルをセンシティブ解除" resolveAbuseReport: "苦情を解決" @@ -2493,6 +2546,26 @@ _reversi: opponentHasSettingsChanged: "相手が設定変えたで" allowIrregularRules: "変則許可 (完全フリー)" disallowIrregularRules: "変則なし" + showBoardLabels: "盤面に行・列番号を表示" + useAvatarAsStone: "石をアイコンにする" _offlineScreen: title: "オフライン - サーバーに接続できひんで" header: "サーバーに接続できへんわ" +_urlPreviewSetting: + title: "URLプレビューの設定" + enable: "URLプレビューを有効にする" + timeout: "プレビュー取得時のタイムアウト(ms)" + timeoutDescription: "プレビュー取得の所要時間がこの値を超えた場合、プレビューは生成されへんで。" + maximumContentLength: "Content-Lengthの最大値(byte)" + maximumContentLengthDescription: "Content-Lengthがこの値を超えた場合、プレビューは生成されへんで。" + requireContentLength: "Content-Lengthが取得できた場合のみプレビューを生成" + requireContentLengthDescription: "相手サーバがContent-Lengthを返さない場合、プレビューは生成されへんで。" + userAgent: "User-Agent" + userAgentDescription: "プレビュー取得時に使用されるUser-Agentを設定するで。空欄の場合、デフォルトのUser-Agentが使用されるで。" + summaryProxy: "プレビューを生成するプロキシのエンドポイント" + summaryProxyDescription: "Misskey本体やなく、サマリープロキシを使用してプレビューを生成するで。" + summaryProxyDescription2: "プロキシには下記パラメータがクエリ文字列として連携されるで。プロキシ側がこれらをサポートせえへんときは、設定値は無視されるで。" +_mediaControls: + pip: "ピクチャインピクチャ" + playbackRate: "再生速度" + loop: "ループ再生" diff --git a/locales/jbo-EN.yml b/locales/jbo-EN.yml index 297ca53dd7..d4fea291d7 100644 --- a/locales/jbo-EN.yml +++ b/locales/jbo-EN.yml @@ -1,4 +1,3 @@ --- _lang_: "la .lojban." headlineMisskey: "lo se tcana noi jorne fi loi notci" - diff --git a/locales/kab-KAB.yml b/locales/kab-KAB.yml index b976f028f0..22e24d3baa 100644 --- a/locales/kab-KAB.yml +++ b/locales/kab-KAB.yml @@ -104,4 +104,3 @@ _deck: _columns: notifications: "Ilɣuyen" list: "Tibdarin" - diff --git a/locales/kn-IN.yml b/locales/kn-IN.yml index bb6d1ee242..b3ad46f2b1 100644 --- a/locales/kn-IN.yml +++ b/locales/kn-IN.yml @@ -84,4 +84,3 @@ _deck: notifications: "ಅಧಿಸೂಚನೆಗಳು" tl: "ಸಮಯಸಾಲು" mentions: "ಹೆಸರಿಸಿದ" - diff --git a/locales/ko-GS.yml b/locales/ko-GS.yml index 39492d902f..9466aff01f 100644 --- a/locales/ko-GS.yml +++ b/locales/ko-GS.yml @@ -16,8 +16,8 @@ cancel: "아이예" noThankYou: "뎃어예" enterUsername: "사용자 이럼 서기" renotedBy: "{user}님이 리노트햇어예" -noNotes: "노트가 없십니다" -noNotifications: "알림이 없십니다" +noNotes: "노트가 어ᇝ십니다" +noNotifications: "알림이 어ᇝ십니다" instance: "서버" settings: "설정" notificationSettings: "알림 설정" @@ -26,7 +26,7 @@ otherSettings: "다린 설정" openInWindow: "창서 옐기" profile: "프로필" timeline: "타임라인" -noAccountDescription: "자기소개가 없십니다" +noAccountDescription: "자기소개가 어ᇝ십니다" login: "로그인" loggingIn: "로그인하고 잇어예" logout: "로그아웃" @@ -80,7 +80,7 @@ unfollowConfirm: "{name}님얼 고마 팔로잉합니꺼?" exportRequested: "내가기 요청얼 햇십니다. 시간이 쪼매 걸릴 깁니다. 요청이 껕나모 ‘드라이브’에 옇십니다." importRequested: "가오기 요청얼 햇십니다. 시간이 쪼매 걸릴 깁니다." lists: "리스트" -noLists: "리스트가 없십니다" +noLists: "리스트가 어ᇝ십니다" note: "노트" notes: "노트" following: "팔로잉" @@ -161,7 +161,7 @@ youCanCleanRemoteFilesCache: "파일 간리으 🗑️ 모냥얼 누질리모 cacheRemoteSensitiveFiles: "웬겍으 수ᇚ힌 파일얼 캐시하기" cacheRemoteSensitiveFilesDescription: "요 설정얼 꺼모 웬겍 수ᇚ힌 파일이 캐시하지 아이하고 바리 링크합니다." flagAsBot: "자동 게정입니다" -flagAsBotDescription: "요 게정얼 프로그램서 설라먼 키야 합니다. 키모 다런 개발자가 반엉얼 끋없이 데풀이하지 몬 하게 도아 줄 수 잇고 Misskey으 시스템서 자동 게정이 뎁니다." +flagAsBotDescription: "요 게정얼 프로그램서 설라먼 키야 합니다. 키모 다런 개발자가 반엉얼 끋어ᇝ이 데풀이하지 몬 하게 도아 줄 수 잇고 Misskey으 시스템서 자동 게정이 뎁니다." flagAsCat: "애웅애웅애웅애웅!" flagAsCatDescription: "애옹?" flagShowTimelineReplies: "타임라인서 노트으 답하기 보기" @@ -176,7 +176,7 @@ wallpaper: "벡지" setWallpaper: "벡지 설정" removeWallpaper: "벡지 뭉캐기" searchWith: "찾기: {q}" -youHaveNoLists: "리스트가 없십니다" +youHaveNoLists: "리스트가 어ᇝ십니다" followConfirm: "{name}님얼 팔로잉합니꺼?" proxyAccount: "프락시 게정" proxyAccountDescription: "프락시 게정언 턱벨한 조겐서 웬겍 팔로잉얼 하넌 게정입니다. 사용자가 웬겍 사용자럴 리스트에 옇얼 때 리스트에 옇언 사용자럴 누도 팔로잉 아이하모 할동이 서버로 아이 오니께 요 게정이 아인 프락시 게정얼 팔로잉하게 합니다." @@ -210,17 +210,17 @@ instanceInfo: "서버 정보" statistics: "통게" clearQueue: "대기옐 비우기" clearQueueConfirmTitle: "대기옐얼 비웁니꺼?" -clearQueueConfirmText: "대기옐에 잇넌 걸얼 아이 보냅니다. 흐이 요 동작언 할 필요가 없십니다." +clearQueueConfirmText: "대기옐에 잇넌 걸얼 아이 보냅니다. 흐이 요 동작언 할 필요가 어ᇝ십니다." clearCachedFiles: "캐시 비우기" clearCachedFilesConfirm: "캐시한 웬겍 파일얼 말캉 뭉캡니꺼?" blockedInstances: "차단한 서버" blockedInstancesDescription: "차단할라넌 서버으 호스트럴 줄 바꿈해서로 비이 줍니다. 차단한 서버넌 요 서버하고 교류 몬 합니다." silencedInstances: "수ᇚ훈 서버" -silencedInstancesDescription: "수ᇚ훌라넌 서버으 호스트럴 줄 바꿈해서로 비이 줍니다. 수ᇚ훈 서버으 게정언 말캉 ‘수ᇚ후기’가 데서 팔로잉 요청만 데고 팔로워가 아인 로컬 게정서 멘션얼 몬 합니다. 차단한 서버넌 상간 없십니다." +silencedInstancesDescription: "수ᇚ훌라넌 서버으 호스트럴 줄 바꿈해서로 비이 줍니다. 수ᇚ훈 서버으 게정언 말캉 ‘수ᇚ후기’가 데서 팔로잉 요청만 데고 팔로워가 아인 로컬 게정서 멘션얼 몬 합니다. 차단한 서버넌 상간 어ᇝ십니다." muteAndBlock: "수ᇚ훔하고 차단" mutedUsers: "수ᇚ훈 사용자" blockedUsers: "차단한 사용자" -noUsers: "사용자가 없십니다" +noUsers: "사용자가 어ᇝ십니다" editProfile: "프로필 적기" noteDeleteConfirm: "요 노트럴 뭉캡니꺼?" pinLimitExceeded: "더 몬 붙입니다" @@ -230,15 +230,15 @@ processing: "처리하고 잇어예" preview: "미리보기" default: "기본값" defaultValueIs: "기본값: {value}" -noCustomEmojis: "이모지가 없십니다" -noJobs: "작업이 없십니다" +noCustomEmojis: "이모지가 어ᇝ십니다" +noJobs: "작업이 어ᇝ십니다" federating: "옌합하고 잇어예" blocked: "차단햇어예" suspended: "고만 보내예" all: "말캉" subscribing: "구독하고 잇어예" publishing: "보내고 잇어예" -notResponding: "답이 없어예" +notResponding: "답이 어ᇝ어예" instanceFollowing: "서버으 팔로잉" instanceFollowers: "서버으 팔로워" instanceUsers: "서버으 사용자" @@ -275,7 +275,7 @@ uploadFromUrlRequested: "올리기럴 요청햇십니다" uploadFromUrlMayTakeTime: "올리기가 껕날라먼 시간이 쪼매 걸릴 깁니다." explore: "살펴보기" messageRead: "이럿어예" -noMoreHistory: "요카마 엣날 기록이 없십니다" +noMoreHistory: "요카마 옛날 기록이 어ᇝ십니다" startMessaging: "대화하기" nUsersRead: "{n}멩이 이럿십니다" agreeTo: "{0}에 동이하기" @@ -432,28 +432,28 @@ securityKey: "보안키" lastUsed: "마지막 쓰임" lastUsedAt: "마지막 쓰임: {t}" unregister: "맨걸기 무루기" -passwordLessLogin: "비밀번호 없시 로그인" -passwordLessLoginDescription: "비밀번호 말고 보안키나 패스키 같은 것만 써 가 로그인합니다." +passwordLessLogin: "비밀번호 어ᇝ이 로그인" +passwordLessLoginDescription: "비밀번호 어ᇝ이 보안 키나 패스 키만 서서 로그인합니다." resetPassword: "비밀번호 재설정" -newPasswordIs: "새 비밀번호는 \"{password}\" 입니다" +newPasswordIs: "새 비밀번호넌 ‘{password}’입니다" reduceUiAnimation: "화면 움직임 효과들을 수ᇚ후기" share: "노누기" notFound: "몬 찾앗십니다" -notFoundDescription: "고런 주소로 들어가는 하멘은 없십니다." -uploadFolder: "기본 업로드 위치" -markAsReadAllNotifications: "모든 알림 이럿다고 표시" -markAsReadAllUnreadNotes: "모든 글 이럿다고 표시" -markAsReadAllTalkMessages: "모든 대화 이럿다고 표시" +notFoundDescription: "선 주소에 맞넌 페이지가 어ᇝ십니다." +uploadFolder: "기본 올리기 위치" +markAsReadAllNotifications: "모던 알림얼 읽엄 포시" +markAsReadAllUnreadNotes: "모던 걸얼 읽엄 포시" +markAsReadAllTalkMessages: "모던 대화 읽엄 포시" help: "도움말" -inputMessageHere: "여따가 메시지를 입력해주이소" -close: "닫기" +inputMessageHere: "옇다 메시지럴 서이소" +close: "꺼기" invites: "초대하기" -members: "멤버" -transfer: "양도" +members: "구성원" +transfer: "넘구기" title: "제목" -text: "글" +text: "걸" enable: "키기" -next: "다음" +next: "다엄" retype: "다시 서기" noteOf: "{user}님으 노트" quoteAttached: "따옴" @@ -468,6 +468,7 @@ tooShort: "억수로 짜립니다" tooLong: "억수로 집니다" passwordMatched: "맞십니다" passwordNotMatched: "안 맞십니다" +signinWith: "{n}서 로그인" signinFailed: "로그인 몬 했십니다. 고 이름이랑 비밀번호 제대로 썼는가 확인해 주이소." or: "아니면" language: "언어" @@ -512,13 +513,13 @@ useObjectStorage: "오브젝트 스토리지 키기" objectStorageBaseUrl: "Base URL" objectStorageBaseUrlDesc: "오브젝트 (미디어) 참조 링크 만들 때 쓰는 URL임다. CDN 내지 프락시를 쓴다 카멘은 그 URL을 갖다 늫고, 아이면 써먹을 서비스네 가이드를 봐봐가 공개적으로 접근할 수 있는 주소를 여 넣어 주이소. 그니께, 내가 AWS S3을 쓴다 카면은 'https://.s3.amazonaws.com', GCS를 쓴다 카면 'https://storage.googleapis.com/' 처럼 쓰믄 되입니더." objectStorageBucket: "Bucket" -objectStorageBucketDesc: "써먹을 서비스의 바께쓰 이름을 여 써 주이소." +objectStorageBucketDesc: "설 서비스으 버킷 이럼얼 서 주이소." objectStoragePrefix: "Prefix" objectStoragePrefixDesc: "요 Prefix 디렉토리 안에다가 파일이 들어감다." objectStorageEndpoint: "Endpoint" -objectStorageEndpointDesc: "AWS S3을 쓸라멘 요는 비워두고, 아이멘은 그 서비스 가이드에 맞게 endpoint를 넣어 주이소. '' 내지 ':'처럼 넣십니다." +objectStorageEndpointDesc: "AWS S3넌 비아 두고 다런 것언 거 서비스으 엔드포인트럴 서 주이소. ‘’나 ‘:’맨치로 섭니다." objectStorageRegion: "Region" -objectStorageRegionDesc: "'xx-east-1' 같은 region 이름을 옇어 주이소. 만약에 내 서비스엔 region 같은 개념이 읎다, 카면은 대신에 'us-east-1'라고 해 두이소. AWS 설정 파일이나 환경 변수를 끌어다 쓰겠다믄 요는 비워 두이소." +objectStorageRegionDesc: "‘xx-east-1’맨치로 리전 이럼얼 서 주이소. 설 서비스에 리전 개넴이 어ᇝ어먼 ‘us-east-1’라고 해 두이소. 에이더블유에스 설정 파일이나 환겡 벤수가 이ᇇ어면 비아 두이소." objectStorageUseSSL: "SSL 쓰기" objectStorageUseSSLDesc: "API 호출할 때 HTTPS 안 쓸거면은 꺼 두이소" objectStorageUseProxy: "연결에 프락시 사용" @@ -534,7 +535,7 @@ newNoteRecived: "새 노트 있어예" sounds: "소리" sound: "소리" listen: "듣기" -none: "없음" +none: "어ᇝ엄" showInPage: "바닥서 보기" popout: "새 창 열기" volume: "음량" @@ -542,13 +543,13 @@ masterVolume: "대빵 음량" notUseSound: "음소거하기" useSoundOnlyWhenActive: "Misskey가 활성화되어 있을 때만 소리 내기" details: "자세히" -chooseEmoji: "이모지 선택" +chooseEmoji: "이모지 개리기" unableToProcess: "작업 다 몬 했십니다" recentUsed: "최근 쓴 놈" install: "설치" uninstall: "삭제" installedApps: "설치된 애플리케이션" -nothing: "뭣도 없어예" +nothing: "어ᇝ어예" installedDate: "설치한 날" lastUsedDate: "마지막 사용" state: "상태" @@ -579,6 +580,7 @@ enableInfiniteScroll: "알아서 더 보기" useCw: "내용 수ᇚ후기" description: "설멩" describeFile: "캡션 옇기" +enterFileDescription: "캡션 서기" author: "맨던 사람" manage: "간리" emailServer: "전자우펜 서버" @@ -598,6 +600,7 @@ reporter: "신고한 사람" reporteeOrigin: "신고덴 사람" reporterOrigin: "신고한 곳" forwardReport: "웬겍 서버에 신고 보내기" +waitingFor: "{x}(얼)럴 지달리고 잇십니다" random: "무작이" system: "시스템" clip: "클립 맨걸기" @@ -610,10 +613,13 @@ followersCount: "팔로워 수" noteFavoritesCount: "질겨찾기한 노트 수" clips: "클립 맨걸기" clearCache: "캐시 비우기" +typingUsers: "{users} 님이 서고 잇어예" unlikeConfirm: "좋네예럴 무룹니꺼?" info: "정보" +selectAccount: "계정 개리기" user: "사용자" administration: "간리" +translatedFrom: "{x}서 번옉" on: "킴" off: "껌" hide: "수ᇚ후기" @@ -625,6 +631,8 @@ oneDay: "하리" oneWeek: "한 주" oneMonth: "한 달" file: "파일" +typeToConfirm: "게속할라먼 {x}럴 누질라 주이소" +pleaseSelect: "개리 주이소" tools: "도구" like: "좋네예!" unlike: "좋네예 무루기" @@ -632,7 +640,7 @@ numberOfLikes: "좋네예 수" show: "보기" roles: "옉할" role: "옉할" -noRole: "옉할이 없십니다" +noRole: "옉할이 어ᇝ십니다" thisPostMayBeAnnoyingCancel: "아이예" likeOnly: "좋네예마" myClips: "내 클립" @@ -641,6 +649,10 @@ replies: "답하기" renotes: "리노트" attach: "옇기" surrender: "아이예" +_delivery: + stop: "고만 보내예" + _type: + none: "보내고 잇어예" _initialAccountSetting: startTutorial: "길라잡이 하기" _initialTutorial: @@ -720,6 +732,7 @@ _theme: _sfx: note: "새 노트" notification: "알림" + reaction: "리액션 개리기" _2fa: step3Title: "학인 기호럴 서기" renewTOTPCancel: "뎃어예" @@ -744,6 +757,9 @@ _cw: _visibility: home: "덜머리" followers: "팔로워" +_postForm: + _placeholders: + e: "옇다 서 주이소" _profile: name: "이럼" username: "사용자 이럼" @@ -796,5 +812,8 @@ _moderationLogTypes: resetPassword: "비밀번호 재설정" resolveAbuseReport: "신고 해겔하기" _reversi: - total: "합계" - + reversi: "리버시" + chooseBoard: "보드 개리기" + black: "꺼멍" + white: "허영" + total: "합게" diff --git a/locales/ko-KR.yml b/locales/ko-KR.yml index 39a186a7f8..69e1216ce4 100644 --- a/locales/ko-KR.yml +++ b/locales/ko-KR.yml @@ -38,9 +38,9 @@ addUser: "유저 추가" favorite: "즐겨찾기" favorites: "즐겨찾기" unfavorite: "즐겨찾기에서 제거" -favorited: "즐겨찾기에 등록했습니다" -alreadyFavorited: "이미 즐겨찾기에 등록되어 있습니다" -cantFavorite: "즐겨찾기에 등록하지 못했습니다" +favorited: "즐겨찾기에 등록했습니다." +alreadyFavorited: "이미 즐겨찾기에 등록했습니다." +cantFavorite: "즐겨찾기에 등록하지 못했습니다." pin: "프로필에 고정" unpin: "프로필에서 고정 해제" copyContent: "내용 복사" @@ -93,7 +93,7 @@ somethingHappened: "오류가 발생했습니다" retry: "다시 시도" pageLoadError: "페이지를 불러오지 못했습니다." pageLoadErrorDescription: "네트워크 연결 또는 브라우저 캐시로 인해 발생했을 가능성이 높습니다. 캐시를 삭제하거나, 잠시 후 다시 시도해 주세요." -serverIsDead: "서버로부터 응답이 없습니다. 잠시 후 다시 시도해주세요." +serverIsDead: "서버가 응답하지 않습니다. 잠시 후 다시 시도해 주세요." youShouldUpgradeClient: "이 페이지를 표시하려면 새로고침하여 새로운 버전의 클라이언트를 이용해 주십시오." enterListName: "리스트 이름을 입력" privacy: "프라이버시" @@ -119,8 +119,8 @@ you: "나" clickToShow: "클릭하여 보기" sensitive: "열람 주의" add: "추가" -reaction: "리액션" -reactions: "리액션" +reaction: "반응" +reactions: "반응" emojiPicker: "이모지 선택기" pinnedEmojisForReactionSettingDescription: "리액션을 할 때 프로필에 고정하여 표시할 이모지를 설정할 수 있습니다" pinnedEmojisSettingDescription: "이모지를 입력할 때 프로필에 고정하여 표시할 이모지를 설정할 수 있습니다" @@ -169,7 +169,7 @@ cacheRemoteSensitiveFilesDescription: "이 설정을 비활성화하면 리모 flagAsBot: "나는 봇입니다" flagAsBotDescription: "이 계정을 자동화된 수단으로 운용할 경우에 활성화해 주세요. 이 플래그를 활성화하면, 다른 봇이 이를 참고하여 봇 끼리의 무한 연쇄 반응을 회피하거나, 이 계정의 시스템 상에서의 취급이 Bot 운영에 최적화되는 등의 변화가 생깁니다." flagAsCat: "미야아아아오오오오오오오오오옹!!!!!!!" -flagAsCatDescription: "야옹?" +flagAsCatDescription: "야옹?(이 계정이 고양이라면 눌러 주세요.)" flagShowTimelineReplies: "타임라인에 노트의 답글을 표시하기" flagShowTimelineRepliesDescription: "이 설정을 활성화하면 타임라인에 다른 유저 간의 답글을 표시합니다." autoAcceptFollowed: "팔로우 중인 유저로부터의 팔로우 요청을 자동 수락" @@ -187,7 +187,7 @@ followConfirm: "{name}님을 팔로우 하시겠습니까?" proxyAccount: "프록시 계정" proxyAccountDescription: "프록시 계정은 특정 조건 하에서 유저의 리모트 팔로우를 대행하는 계정입니다. 예를 들면, 유저가 리모트 유저를 리스트에 넣었을 때, 리스트에 들어간 유저를 아무도 팔로우한 적이 없다면 액티비티가 서버로 배달되지 않기 때문에, 대신 프록시 계정이 해당 유저를 팔로우하도록 합니다." host: "호스트" -selectUser: "유저 선택" +selectUser: "사용자 선택" recipient: "수신인" annotation: "내용에 대한 주석" federation: "연합" @@ -230,7 +230,7 @@ noUsers: "아무도 없습니다" editProfile: "프로필 수정" noteDeleteConfirm: "이 노트를 삭제하시겠습니까?" pinLimitExceeded: "더 이상 고정할 수 없습니다." -intro: "Misskey의 설치가 완료되었습니다! 관리자 계정을 생성해주세요." +intro: "Misskey의 설치를 완료했습니다! 관리자 계정을 만들어 주세요." done: "완료" processing: "처리중" preview: "미리보기" @@ -296,7 +296,7 @@ activity: "활동" images: "이미지" image: "이미지" birthday: "생일" -yearsOld: "{age}세" +yearsOld: "만 {age} 세" registeredDate: "등록일" location: "장소" theme: "테마" @@ -400,6 +400,7 @@ name: "이름" antennaSource: "받을 소스" antennaKeywords: "받을 검색어" antennaExcludeKeywords: "제외할 검색어" +antennaExcludeBots: "봇 계정 제외" antennaKeywordsDescription: "공백으로 구분하는 경우 AND, 줄바꿈으로 구분하는 경우 OR로 지정됩니다" notifyAntenna: "새로운 노트를 알림" withFileAntenna: "파일이 첨부된 노트만" @@ -414,11 +415,11 @@ silence: "사일런스" silenceConfirm: "이 계정을 사일런스로 설정하시겠습니까?" unsilence: "사일런스 해제" unsilenceConfirm: "이 계정의 사일런스를 해제하시겠습니까?" -popularUsers: "인기 유저" -recentlyUpdatedUsers: "최근 활동한 유저" -recentlyRegisteredUsers: "최근 가입한 유저" -recentlyDiscoveredUsers: "최근 발견한 유저" -exploreUsersCount: "{count}명의 유저가 있습니다" +popularUsers: "인기 사용자" +recentlyUpdatedUsers: "최근에 활동한 사용자" +recentlyRegisteredUsers: "최근에 가입한 사용자" +recentlyDiscoveredUsers: "최근에 발견한 사용자" +exploreUsersCount: "{count}명의 사용자가 있습니다" exploreFediverse: "연합우주를 탐색" popularTags: "인기 태그" userList: "리스트" @@ -470,7 +471,7 @@ quoteQuestion: "인용해서 작성하시겠습니까?" noMessagesYet: "아직 대화가 없습니다" newMessageExists: "새 메시지가 있습니다" onlyOneFileCanBeAttached: "메시지에 첨부할 수 있는 파일은 하나까지입니다" -signinRequired: "로그인 해주세요" +signinRequired: "진행하기 전에 로그인을 해 주세요" invitations: "초대" invitationCode: "초대 코드" checking: "확인하는 중입니다" @@ -494,6 +495,7 @@ emojiStyle: "이모지 스타일" native: "기본" disableDrawer: "드로어 메뉴를 사용하지 않기" showNoteActionsOnlyHover: "노트 액션 버튼을 마우스를 올렸을 때에만 표시" +showReactionsCount: "노트의 반응 수를 표시하기" noHistory: "기록이 없습니다" signinHistory: "로그인 기록" enableAdvancedMfm: "고급 MFM을 활성화" @@ -529,13 +531,13 @@ useObjectStorage: "오브젝트 스토리지를 사용" objectStorageBaseUrl: "Base URL" objectStorageBaseUrlDesc: "오브젝트 (미디어) 참조 URL 을 만들 때 사용되는 URL입니다. CDN 또는 프록시를 사용하는 경우 그 URL을 지정하고, 그 외의 경우 사용할 서비스의 가이드에 따라 공개적으로 액세스 할 수 있는 주소를 지정해 주세요. 예를 들어, AWS S3의 경우 'https://.s3.amazonaws.com', GCS등의 경우 'https://storage.googleapis.com/' 와 같이 지정합니다." objectStorageBucket: "Bucket" -objectStorageBucketDesc: "사용 서비스의 bucket명을 지정해주세요." +objectStorageBucketDesc: "사용하는 서비스의 bucket 이름을 지정해 주세요." objectStoragePrefix: "Prefix" objectStoragePrefixDesc: "이 Prefix 의 디렉토리 아래에 파일이 저장됩니다." objectStorageEndpoint: "Endpoint" -objectStorageEndpointDesc: "AWS S3의 경우 공란, 다른 서비스의 경우 각 서비스의 가이드에 맞게 endpoint를 설정해주세요. '' 혹은 ':' 와 같이 지정합니다." +objectStorageEndpointDesc: "AWS S3는 비워 두고 다른 서비스는 각 서비스의 endpoint를 설정해 주세요. ‘’ 혹은 ‘:’처럼 지정합니다." objectStorageRegion: "Region" -objectStorageRegionDesc: "'xx-east-1'와 같이 region을 지정해 주세요. 사용하는 서비스에 region 개념이 없는 경우 'us-east-1'으로 설정해 주세요. AWS 설정 파일 또는 환경 변수를 참조할 경우에는 비워주세요." +objectStorageRegionDesc: "‘xx-east-1’처럼 region을 지정해 주세요. 사용하는 서비스에 region 개념이 없으면 ‘us-east-1’처럼 설정해 주세요. AWS 설정 파일이나 환경 변수가 있으면 비워 주세요." objectStorageUseSSL: "SSL 사용" objectStorageUseSSLDesc: "API 호출시 HTTPS 를 사용하지 않는 경우 OFF 로 설정해 주세요" objectStorageUseProxy: "연결에 프록시를 사용" @@ -577,7 +579,7 @@ scratchpadDescription: "스크래치 패드는 AiScript 의 테스트 환경을 output: "출력" script: "스크립트" disablePagesScript: "Pages 에서 AiScript 를 사용하지 않음" -updateRemoteUser: "리모트 유저 정보 갱신" +updateRemoteUser: "원격 사용자 정보 갱신" unsetUserAvatar: "아바타 제거" unsetUserAvatarConfirm: "아바타를 제거할까요?" unsetUserBanner: "배너 제거" @@ -660,7 +662,7 @@ regexpErrorDescription: "{tab}단어 뮤트 {line}행의 정규 표현식에 오 instanceMute: "서버 뮤트" userSaysSomething: "{name}님이 무언가를 말했습니다" makeActive: "활성화" -display: "표시" +display: "보기" copy: "복사" metrics: "통계" overview: "요약" @@ -684,7 +686,7 @@ sample: "예시" abuseReports: "신고" reportAbuse: "신고" reportAbuseRenote: "리노트 신고하기" -reportAbuseOf: "{name}을 신고하기" +reportAbuseOf: "{name} 신고하기" fillAbuseReportDescription: "신고하려는 이유를 자세히 알려주세요. 특정 게시물을 신고할 때에는 게시물의 URL도 포함해 주세요." abuseReported: "신고를 보냈습니다. 신고해 주셔서 감사합니다." reporter: "신고자" @@ -709,7 +711,7 @@ createNew: "새로 만들기" optional: "옵션" createNewClip: "새 클립 만들기" unclip: "클립 해제" -confirmToUnclipAlreadyClippedNote: "이 노트는 이미 \"{name}\" 클립에 포함되어 있습니다. 클립을 해제하시겠습니까?" +confirmToUnclipAlreadyClippedNote: "이 노트는 ‘{name}’ 클립을 이미 포함합니다. 클립에서 제외하시겠습니까?" public: "공개" private: "비공개" i18nInfo: "Misskey는 자원봉사자들에 의해 다양한 언어로 번역되고 있습니다. {link}에서 번역에 참가할 수 있습니다." @@ -722,13 +724,13 @@ repliedCount: "받은 답글 수" renotedCount: "받은 리노트 수" followingCount: "팔로우 수" followersCount: "팔로워 수" -sentReactionsCount: "보낸 리액션 수" -receivedReactionsCount: "받은 리액션 수" -pollVotesCount: "투표한 횟수" -pollVotedCount: "투표받은 횟수" +sentReactionsCount: "반응 수" +receivedReactionsCount: "받은 반응 수" +pollVotesCount: "투표 수" +pollVotedCount: "받은 투표 수" yes: "예" no: "아니오" -driveFilesCount: "드라이브 파일 개수" +driveFilesCount: "드라이브에 있는 파일 수" driveUsage: "드라이브 사용량" noCrawle: "검색엔진의 인덱싱 거부" noCrawleDescription: "검색엔진에 사용자 페이지, 노트, 페이지 등의 콘텐츠를 인덱싱되지 않게 합니다." @@ -763,7 +765,7 @@ needReloadToApply: "변경 사항은 새로고침하면 적용됩니다." showTitlebar: "타이틀 바를 표시하기" clearCache: "캐시 비우기" onlineUsersCount: "{n}명이 접속 중" -nUsers: "{n} 유저" +nUsers: "{n} 사용자" nNotes: "{n} 노트" sendErrorReports: "오류 보고서 보내기" sendErrorReportsDescription: "이 설정을 활성화하면, 문제가 발생했을 때 오류에 대한 상세 정보를 Misskey에 보내어 더 나은 소프트웨어를 만드는 데에 도움을 줄 수 있습니다." @@ -809,7 +811,7 @@ addDescription: "설명 추가" userPagePinTip: "각 노트의 메뉴에서 「프로필에 고정」을 선택하는 것으로, 여기에 노트를 표시해 둘 수 있어요." notSpecifiedMentionWarning: "수신자가 선택되지 않은 멘션이 있어요" info: "정보" -userInfo: "유저 정보" +userInfo: "사용자 정보" unknown: "알 수 없음" onlineStatus: "온라인 상태" hideOnlineStatus: "온라인 상태 숨기기" @@ -897,7 +899,7 @@ incorrectPassword: "비밀번호가 올바르지 않습니다." voteConfirm: "\"{choice}\"에 투표하시겠습니까?" hide: "숨기기" useDrawerReactionPickerForMobile: "모바일에서 드로어 메뉴로 표시" -welcomeBackWithName: "환영합니다, {name}님" +welcomeBackWithName: "{name}님, 환영합니다." clickToFinishEmailVerification: "[{ok}]를 눌러 이메일 인증을 완료하세요." overridedDeviceKind: "장치 유형" smartphone: "스마트폰" @@ -1092,9 +1094,9 @@ preservedUsernames: "예약된 사용자명" preservedUsernamesDescription: "예약할 사용자명을 한 줄에 하나씩 입력합니다. 여기에서 지정한 사용자명으로는 계정을 생성할 수 없게 됩니다. 단, 관리자 권한으로 계정을 생성할 때에는 해당되지 않으며, 이미 존재하는 계정도 영향을 받지 않습니다." createNoteFromTheFile: "이 파일로 노트를 작성" archive: "아카이브" -channelArchiveConfirmTitle: "{name} 을(를) 아카이브하시겠습니까?" -channelArchiveConfirmDescription: "아카이브한 채널은 채널 목록과 검색 결과에 표시되지 않으며, 채널에 새로운 노트를 작성할 수 없게 됩니다." -thisChannelArchived: "이 채널은 아카이브되었습니다." +channelArchiveConfirmTitle: "{name} 채널을 보존하시겠습니까?" +channelArchiveConfirmDescription: "보존한 채널은 채널 목록과 검색 결과에 표시되지 않으며 새로운 노트도 작성할 수 없습니다." +thisChannelArchived: "이 채널은 보존되었습니다." displayOfNote: "노트 표시" initialAccountSetting: "초기 설정" youFollowing: "팔로잉" @@ -1156,10 +1158,11 @@ unnotifyNotes: "새 노트 알림 끄기" authentication: "인증" authenticationRequiredToContinue: "계속하려면 인증하십시오" dateAndTime: "일시" -showRenotes: "리노트 표시" +showRenotes: "리노트 보기" edited: "수정됨" notificationRecieveConfig: "알림 설정" mutualFollow: "맞팔로우" +followingOrFollower: "팔로 중이거나 팔로워" fileAttachedOnly: "미디어를 포함한 노트만" showRepliesToOthersInTimeline: "타임라인에 다른 사람에게 보내는 답글을 포함" hideRepliesToOthersInTimeline: "타임라인에 다른 사람에게 보내는 답글을 포함하지 않음" @@ -1210,16 +1213,38 @@ soundWillBePlayed: "소리가 재생됩니다" showReplay: "리플레이 보기" replay: "리플레이" replaying: "리플레이 중" +endReplay: "리플레이 종료" +copyReplayData: "리플레이 데이터를 복사" ranking: "랭킹" lastNDays: "최근 {n}일" backToTitle: "타이틀로 가기" hemisphere: "거주 지역" withSensitive: "민감한 파일이 포함된 노트 보기" -userSaysSomethingSensitive: "{name}의 민감한 파일이 포함된 게시물" +userSaysSomethingSensitive: "{name} 같은 민감한 파일이 포함된 글" enableHorizontalSwipe: "스와이프하여 탭 전환" +loading: "불러오는 중" surrender: "그만두기" +gameRetry: "다시 시도" +notUsePleaseLeaveBlank: "사용하지 않는 경우 비워두세요." +useTotp: "일회용 비밀번호 사용" +useBackupCode: "백업 코드 사용" +launchApp: "앱 실행" +useNativeUIForVideoAudioPlayer: "브라우저 UI에서 미디어 재생" +_delivery: + stop: "정지됨" + _type: + none: "배포 중" _bubbleGame: howToPlay: "설명" + hold: "홀드" + _score: + score: "점수" + scoreYen: "번 돈" + highScore: "최고 점수" + maxChain: "최대 콤보 수" + yen: "{yen}엔" + estimatedQty: "{qty}개" + scoreSweets: "오니기리 {onigiriQtyWithUnit}" _howToPlay: section1: "위치를 조정하여 상자에 물건을 떨어뜨립니다." section2: "같은 종류의 물건이 붙으면 다른 물건으로 바뀌면서 점수를 얻게 됩니다." @@ -1232,7 +1257,7 @@ _announcement: end: "공지에서 내리기" tooManyActiveAnnouncementDescription: "공지사항이 너무 많을 경우, 사용자 경험에 영향을 끼칠 가능성이 있습니다. 오래된 공지사항은 아카이브하시는 것을 권장드립니다." readConfirmTitle: "읽음으로 표시합니까?" - readConfirmText: "\"{title}\"을(를) 읽음으로 표시합니다." + readConfirmText: "〈{title}〉의 내용을 읽음으로 표시합니다." shouldNotBeUsedToPresentPermanentInfo: "신규 유저의 이용 경험에 악영향을 끼칠 수 있으므로, 일시적인 알림 수단으로만 사용하고 고정된 정보에는 사용을 지양하는 것을 추천합니다." dialogAnnouncementUxWarn: "다이얼로그 형태의 알림이 동시에 2개 이상 존재하는 경우, 사용자 경험에 악영향을 끼칠 수 있으므로 신중히 결정하십시오." silence: "조용히 알림" @@ -1513,7 +1538,7 @@ _achievements: _iLoveMisskey: title: "I Love Misskey" description: "\"I ❤ #Misskey\"를 포스트했습니다" - flavor: "Misskey를 이용해주셔서 감사합니다! - 개발팀 일동" + flavor: "Misskey를 이용해 주셔서 감사합니다! ― 개발 팀" _foundTreasure: title: "보물찾기" description: "숨겨진 보물을 발견했습니다" @@ -1551,10 +1576,10 @@ _achievements: description: "3개 이상의 창을 열었습니다" _driveFolderCircularReference: title: "순환 참조" - description: "드라이브 폴더를 자신을 가리키도록 만드려 시도했습니다" + description: "드라이브 폴더에 스스로를 넣게 했습니다" _reactWithoutRead: title: "읽고 답하긴 하시는 건가요?" - description: "100자가 넘는 노트가 작성되고 3초 안에 반응했습니다" + description: "100자가 넘는 노트를 작성한 지 3초 안에 반응했어요" _clickedClickHere: title: "여기를 누르세요" description: "여기를 눌렀습니다" @@ -1641,6 +1666,7 @@ _role: gtlAvailable: "글로벌 타임라인 보이기" ltlAvailable: "로컬 타임라인 보이기" canPublicNote: "공개 노트 허용" + mentionMax: "노트에 넣을 수 있는 멘션 수" canInvite: "서버 초대 코드 발행" inviteLimit: "초대 한도" inviteLimitCycle: "초대 발급 간격" @@ -1650,13 +1676,13 @@ _role: driveCapacity: "드라이브 용량" alwaysMarkNsfw: "파일을 항상 NSFW로 지정" pinMax: "고정할 수 있는 노트 수" - antennaMax: "최대 안테나 생성 허용 수" + antennaMax: "만들 수 있는 안테나 수" wordMuteMax: "단어 뮤트할 수 있는 문자 수" - webhookMax: "생성할 수 있는 웹훅 수" - clipMax: "생성할 수 있는 클립 수" - noteEachClipsMax: "각 클립에 추가할 수 있는 노트 수" - userListMax: "생성할 수 있는 유저 리스트 수" - userEachUserListsMax: "유저 리스트당 최대 사용자 수" + webhookMax: "만들 수 있는 웹후크 수" + clipMax: "만들 수 있는 클립 수" + noteEachClipsMax: "클립에 넣을 수 있는 노트 수" + userListMax: "만들 수 있는 사용자 리스트 수" + userEachUserListsMax: "사용자 리스트에 넣을 수 있는 사용자 수" rateLimitFactor: "요청 빈도 제한" descriptionOfRateLimitFactor: "작을수록 제한이 완화되고, 클수록 제한이 강화됩니다." canHideAds: "광고 숨기기" @@ -1664,16 +1690,17 @@ _role: canUseTranslator: "번역 기능의 사용" avatarDecorationLimit: "아바타 장식의 최대 붙임 개수" _condition: + roleAssignedTo: "수동 역할에 이미 할당됨" isLocal: "로컬 사용자" isRemote: "리모트 사용자" createdLessThan: "가입한 지 다음 일수 이내인 유저" createdMoreThan: "가입한 지 다음 일수 이상인 유저" followersLessThanOrEq: "팔로워 수가 다음 이하인 유저" - followersMoreThanOrEq: "팔로워 수가 다음 이상인 유저" + followersMoreThanOrEq: "팔로워 수가 다음보다 많은 사용자" followingLessThanOrEq: "팔로잉 수가 다음 이하인 유저" - followingMoreThanOrEq: "팔로잉 수가 다음 이상인 유저" + followingMoreThanOrEq: "팔로잉 수가 다음보다 많은 사용자" notesLessThanOrEq: "노트 수가 다음 이하인 유저" - notesMoreThanOrEq: "노트 수가 다음 이상인 유저" + notesMoreThanOrEq: "노트 수가 다음보다 많은 사용자" and: "다음을 모두 만족" or: "다음을 하나라도 만족" not: "다음을 만족하지 않음" @@ -1735,6 +1762,7 @@ _plugin: installWarn: "신뢰할 수 없는 플러그인은 설치하지 않는 것이 좋습니다." manage: "플러그인 관리" viewSource: "소스 보기" + viewLog: "로그 보기" _preferencesBackups: list: "생성한 백업" saveNew: "새 백업 만들기" @@ -1745,12 +1773,12 @@ _preferencesBackups: cannotSave: "저장하지 못했습니다" nameAlreadyExists: "\"{name}\" 백업이 이미 존재합니다. 다른 이름을 설정하여 주십시오." applyConfirm: "\"{name}\" 백업을 현재 기기에 적용하시겠습니까? 현재 설정은 덮어 씌워집니다." - saveConfirm: "{name} 을 덮어쓰시겠습니까?" - deleteConfirm: "{name} 을(를) 삭제하시겠습니까?" - renameConfirm: "\"{old}\" 백업을 \"{new}\"(으)로 바꾸시겠습니까?" + saveConfirm: "{name} 백업을 덮어쓰시겠습니까?" + deleteConfirm: "{name} 백업을 삭제하시겠습니까?" + renameConfirm: "‘{old}’ 백업을 ‘{new}’ 백업으로 바꾸시겠습니까?" noBackups: "저장된 백업이 없습니다. \"새 백업 만들기\"를 눌러 현재 클라이언트 설정을 서버에 백업할 수 있습니다." - createdAt: "생성 날짜: {date} {time}" - updatedAt: "갱신 날짜: {date} {time}" + createdAt: "만든 날짜: {date} {time}" + updatedAt: "고친 날짜: {date} {time}" cannotLoad: "가져오기에 실패했습니다" invalidFile: "파일 형식이 올바르지 않습니다." _registry: @@ -1924,7 +1952,6 @@ _2fa: registerTOTP: "인증 앱 설정 시작" step1: "먼저, {a}나 {b}등의 인증 앱을 사용 중인 디바이스에 설치합니다." step2: "그 후, 표시되어 있는 QR코드를 앱으로 스캔합니다." - step2Click: "QR 코드를 클릭하면 기기에 설치된 인증 앱에 등록할 수 있습니다." step2Uri: "데스크톱 앱을 사용하려면 다음 URI를 입력하십시오" step3Title: "인증 코드 입력" step3: "앱에 표시된 토큰을 입력하시면 완료됩니다." @@ -1937,7 +1964,7 @@ _2fa: securityKeyName: "키 이름 입력" tapSecurityKey: "브라우저의 지시에 따라 보안 키 또는 패스키를 등록하여 주십시오" removeKey: "보안 키를 삭제" - removeKeyConfirm: "{name} 을(를) 삭제하시겠습니까?" + removeKeyConfirm: "{name} 앱을 삭제하시겠습니까?" whyTOTPOnlyRenew: "보안 키가 등록되어 있는 경우 인증 앱을 해제할 수 없습니다." renewTOTP: "인증 앱 재설정" renewTOTPConfirm: "기존에 등록되어 있던 인증 키는 사용하지 못하게 됩니다." @@ -1998,7 +2025,6 @@ _permissions: "read:admin:server-info": "서버 정보 보기" "read:admin:show-moderation-log": "조정 기록 보기" "read:admin:show-user": "사용자 개인정보 보기" - "read:admin:show-users": "사용자 개인정보 보기" "write:admin:suspend-user": "사용자 정지하기" "write:admin:unset-user-avatar": "사용자 아바타 삭제하기" "write:admin:unset-user-banner": "사용자 배너 삭제하기" @@ -2078,7 +2104,7 @@ _widgets: postForm: "글 입력란" slideshow: "슬라이드 쇼" button: "버튼" - onlineUsers: "온라인 유저" + onlineUsers: "온라인 사용자" jobQueue: "작업 대기열" serverMetric: "서버 통계" aiscript: "AiScript 콘솔" @@ -2137,10 +2163,10 @@ _postForm: c: "무엇을 생각하고 있나요?" d: "말하고 싶은 게 있나요?" e: "여기에 적어 주세요" - f: "작성해주시길 기다리고 있어요..." + f: "글 쓰기를 기다려요…" _profile: name: "이름" - username: "유저명" + username: "사용자 이름" description: "자기소개" youCanIncludeHashtags: "해시 태그를 포함할 수 있습니다." metadata: "추가 정보" @@ -2168,7 +2194,7 @@ _charts: apRequest: "요청" usersIncDec: "유저 수 증감" usersTotal: "유저 수 합계" - activeUsers: "활성 유저 수" + activeUsers: "활동 사용자 수" notesIncDec: "노트 수 증감" localNotesIncDec: "로컬 노트 수 증감" remoteNotesIncDec: "리모트 노트 수 증감" @@ -2179,8 +2205,8 @@ _charts: storageUsageTotal: "스토리지 사용량 합계" _instanceCharts: requests: "요청" - users: "유저 수 증감" - usersTotal: "누적 유저 수" + users: "사용자 수 차이" + usersTotal: "누적 사용자 수" notes: "노트 수 증감" notesTotal: "누적 노트 수" ff: "팔로잉/팔로워 증감" @@ -2209,6 +2235,7 @@ _play: title: "제목" script: "스크립트" summary: "설명" + visibilityDescription: "비공개로 설정하면 프로필에 표시하지 않지만 URL을 아는 사람은 계속해서 접속할 수 있습니다." _pages: newPage: "페이지 만들기" editPage: "페이지 수정" @@ -2219,7 +2246,7 @@ _pages: pageSetting: "페이지 설정" nameAlreadyExists: "지정한 페이지 URL이 이미 존재합니다" invalidNameTitle: "유효하지 않은 페이지 URL입니다" - invalidNameText: "비어있지 않은지 확인해주세요" + invalidNameText: "비어있는지 확인해 주세요" editThisPage: "이 페이지를 편집" viewSource: "소스 보기" viewPage: "페이지 보기" @@ -2253,6 +2280,8 @@ _pages: section: "섹션" image: "이미지" button: "버튼" + dynamic: "동적 블록" + dynamicDescription: "이 블록은 폐지되었습니다. 이제부터 {play}에서 이용해 주세요." note: "노트필기" _note: id: "노트 ID" @@ -2282,17 +2311,19 @@ _notification: sendTestNotification: "테스트 알림 보내기" notificationWillBeDisplayedLikeThis: "알림이 이렇게 표시됩니다" reactedBySomeUsers: "{n}명이 반응했습니다" + likedBySomeUsers: "{n}명이 좋아요를 했습니다" renotedBySomeUsers: "{n}명이 리노트했습니다" followedBySomeUsers: "{n}명에게 팔로우됨" + flushNotification: "알림 이력을 초기화" _types: all: "전부" - note: "유저의 새 게시물" + note: "사용자의 새 글" follow: "팔로잉" mention: "멘션" reply: "답글" renote: "리노트" quote: "인용" - reaction: "리액션" + reaction: "반응" pollEnded: "투표가 종료됨" receiveFollowRequest: "팔로우 요청을 받았을 때" followRequestAccepted: "팔로우 요청이 승인되었을 때" @@ -2335,7 +2366,7 @@ _deck: direct: "다이렉트" roleTimeline: "역할 타임라인" _dialog: - charactersExceeded: "최대 글자수를 초과하였습니다! 현재 {current} / 최대 {min}" + charactersExceeded: "최대 글자수를 초과하였습니다! 현재 {current} / 최대 {max}" charactersBelow: "최소 글자수 미만입니다! 현재 {current} / 최소 {min}" _disabledTimeline: title: "비활성화된 타임라인" @@ -2459,7 +2490,7 @@ _dataSaver: _hemisphere: N: "북반구" S: "남반구" - caption: "일부 클라이언트 설정에서 계절을 판단하기 위해 사용합니다." + caption: "일부 클라이언트 설정에서 계절을 판단하려고 사용합니다." _reversi: reversi: "리버시" gameSettings: "대국 설정" @@ -2467,41 +2498,61 @@ _reversi: blackOrWhite: "선공/후공" blackIs: "{name}님이 흑(선공)" rules: "규칙" - thisGameIsStartedSoon: "대국이 곧 시작됩니다" - waitingForOther: "상대방의 준비가 완료되기를 기다리고 있습니다." - waitingForMe: "당신의 준비가 완료되기를 기다리고 있습니다." + thisGameIsStartedSoon: "대국을 곧 시작합니다" + waitingForOther: "상대의 준비가 끝나기를 기다리고 있습니다." + waitingForMe: "나의 준비가 끝나기를 기다리고 있습니다." waitingBoth: "준비하세요" ready: "준비 완료" - cancelReady: "준비 다시 시작" + cancelReady: "준비되지 않음" opponentTurn: "상대의 차례입니다" - myTurn: "당신의 차례입니다" - turnOf: "{name}의 차례입니다" - pastTurnOf: "{name}의 차례" + myTurn: "나의 차례입니다" + turnOf: "{name}님의 차례입니다" + pastTurnOf: "{name}님의 차례" surrender: "기권" - surrendered: "기권에 의해" + surrendered: "상대의 기권" timeout: "시간 초과" drawn: "무승부" - won: "{name}의 승리" + won: "{name}님의 승리" black: "흑" white: "백" total: "합계" - turnCount: "{count}턴 째" + turnCount: "{count}번째 수" myGames: "내 대국" - allGames: "모두의 대국" + allGames: "모든 대국" ended: "종료" playing: "대국 중" - isLlotheo: "돌이 적은 사람이 승리 (로세오)" - loopedMap: "루프 지도" - canPutEverywhere: "어디에도 둘 수 있는 모드" - timeLimitForEachTurn: "1턴의 시간 제한" - freeMatch: "프리매치" - lookingForPlayer: "상대를 찾고 있습니다" + isLlotheo: "돌이 적은 쪽이 승리(로세오)" + loopedMap: "순환 지도" + canPutEverywhere: "어디든 둘 수 있는 모드" + timeLimitForEachTurn: "각 수의 시간 제한" + freeMatch: "자유 대국" + lookingForPlayer: "대국 상대를 찾고 있습니다" gameCanceled: "대국이 취소되었습니다" - shareToTlTheGameWhenStart: "대국 시작 시 타임라인에 대국을 게시" - iStartedAGame: "대국이 시작되었습니다! #MisskeyReversi" - opponentHasSettingsChanged: "상대방이 설정을 변경했습니다" - allowIrregularRules: "규칙변경 허가 (완전 자유)" - disallowIrregularRules: "규칙변경 없음" + shareToTlTheGameWhenStart: "대국이 시작할 때 타임라인에 공유" + iStartedAGame: "대국을 시작하였습니다! #MisskeyReversi" + opponentHasSettingsChanged: "상대가 설정을 변경했습니다" + allowIrregularRules: "규칙 변경 허용(완전 자유)" + disallowIrregularRules: "규칙 변경 없음" + showBoardLabels: "판에 행·열 번호 표시" + useAvatarAsStone: "돌을 아이콘으로 표시" _offlineScreen: title: "오프라인 - 서버에 접속할 수 없습니다" header: "서버에 접속할 수 없습니다" +_urlPreviewSetting: + title: "URL 미리보기 설정" + enable: "URL 미리보기 활성화" + timeout: "미리보기를 불러올 때의 타임아웃 (ms)" + timeoutDescription: "미리보기를 로딩하는데 걸리는 시간이 정한 시간보다 오래 걸리는 경우, 미리보기를 생성하지 않습니다." + maximumContentLength: "Content-Length의 최대치 (byte)" + maximumContentLengthDescription: "Content-Length가 이 값을 넘어서면 미리보기를 생성하지 않습니다." + requireContentLength: "Content-Length를 얻었을 때만 미리보기 만들기" + requireContentLengthDescription: "상대 서버가 Content-Length를 되돌려주지 않는다면 미리보기를 만들지 않습니다." + userAgent: "User-Agent" + userAgentDescription: "미리보기를 얻을 때 사용한 User-Agent를 설정합니다. 비어 있다면 기본값의 User-Agent를 사용합니다." + summaryProxy: "미리보기를 만든 프록시의 엔드포인트" + summaryProxyDescription: "Misskey 본체를 사용하지 않고 서머리 프록시로 미리보기를 만듭니다." + summaryProxyDescription2: "프록시는 아래의 파라미터를 쿼리 문자열로 연동합니다. 프록시 측이 이를 지원하지 않으면 설정값을 무시합니다." +_mediaControls: + pip: "화면 속 화면" + playbackRate: "재생 속도" + loop: "반복 재생" diff --git a/locales/lo-LA.yml b/locales/lo-LA.yml index 6f03c914fd..087bac3745 100644 --- a/locales/lo-LA.yml +++ b/locales/lo-LA.yml @@ -395,6 +395,10 @@ searchByGoogle: "ຄົ້ນຫາ" file: "ໄຟລ໌" replies: "ຕອບ​ໄປ​ທີ" renotes: "Renote" +_delivery: + stop: "ໂຈະ" + _type: + none: "ການ​ພິມ​ເຜີຍ​ແຜ່" _role: _priority: middle: "ປານກາງ" @@ -466,4 +470,3 @@ _webhookSettings: name: "ຊື່" _moderationLogTypes: suspend: "ລະງັບ" - diff --git a/locales/nl-NL.yml b/locales/nl-NL.yml index 42fbf183be..2154e248af 100644 --- a/locales/nl-NL.yml +++ b/locales/nl-NL.yml @@ -429,6 +429,10 @@ loggedInAsBot: "Momenteel als bot ingelogd" icon: "Avatar" replies: "Antwoorden" renotes: "Herdelen" +_delivery: + stop: "Opgeschort" + _type: + none: "Publiceren" _email: _follow: title: "volgde jou" @@ -497,4 +501,3 @@ _webhookSettings: _moderationLogTypes: suspend: "Opschorten" resetPassword: "Wachtwoord terugzetten" - diff --git a/locales/no-NO.yml b/locales/no-NO.yml index 098faa8add..2b4c9b7776 100644 --- a/locales/no-NO.yml +++ b/locales/no-NO.yml @@ -464,6 +464,8 @@ icon: "Avatar" replies: "Svar" renotes: "Renote" surrender: "Avbryt" +_delivery: + stop: "Suspendert" _initialAccountSetting: theseSettingsCanEditLater: "Du kan endre disse innstillingene senere." _achievements: @@ -721,4 +723,3 @@ _webhookSettings: name: "Navn" _moderationLogTypes: suspend: "Suspender" - diff --git a/locales/pl-PL.yml b/locales/pl-PL.yml index b7566aaa46..4acd6af991 100644 --- a/locales/pl-PL.yml +++ b/locales/pl-PL.yml @@ -20,6 +20,7 @@ noNotes: "Brak wpisów" noNotifications: "Brak powiadomień" instance: "Instancja" settings: "Ustawienia" +notificationSettings: "Powiadomienia" basicSettings: "Podstawowe ustawienia" otherSettings: "Pozostałe ustawienia" openInWindow: "Otwórz w oknie" @@ -44,13 +45,20 @@ pin: "Przypnij do profilu" unpin: "Odepnij z profilu" copyContent: "Skopiuj zawartość" copyLink: "Skopiuj odnośnik" +copyLinkRenote: "Skopiuj link renote'a" delete: "Usuń" deleteAndEdit: "Usuń i edytuj" deleteAndEditConfirm: "Czy na pewno chcesz usunąć ten wpis i zedytować go? Utracisz wszystkie reakcje, udostępnienia i odpowiedzi do tego wpisu." addToList: "Dodaj do listy" +addToAntenna: "Dodaj do anteny" sendMessage: "Wyślij wiadomość" copyRSS: "Kopiuj RSS" copyUsername: "Kopiuj nazwę użytkownika" +copyUserId: "Kopiuj ID użytkownika" +copyNoteId: "Kopiuj ID notatki" +copyFileId: "Kopiuj ID pliku" +copyFolderId: "Kopiuj ID folderu" +copyProfileUrl: "Kopiuj URL profilu" searchUser: "Wyszukiwanie użytkowników" reply: "Odpowiedz" loadMore: "Załaduj więcej" @@ -103,6 +111,8 @@ renoted: "Udostępniono." cantRenote: "Ten wpis nie może zostać udostępniony." cantReRenote: "Udostępnienie nie może zostać udostępnione." quote: "Cytuj" +inChannelRenote: "Renote tylko na kanale" +inChannelQuote: "Cytat tylko na kanale" pinnedNote: "Przypięty wpis" pinned: "Przypnij do profilu" you: "Ty" @@ -111,14 +121,23 @@ sensitive: "NSFW" add: "Dodaj" reaction: "Reakcja" reactions: "Reakcja" +emojiPicker: "Selektor Emoji" +pinnedEmojisForReactionSettingDescription: "Ustaw emotikony które powinny być przypięte i od razu wyświetlone podczas reagowania." +pinnedEmojisSettingDescription: "Ustaw emotikony które powinny być przypięte i wyświetlone podczas przeglądania selektora Emoji" +emojiPickerDisplay: "Wyświetlanie selektora Emoji" +overwriteFromPinnedEmojisForReaction: "Zastąp z ustawień reakcji" +overwriteFromPinnedEmojis: "Zastąp z ogólnych ustawień" reactionSettingDescription2: "Przeciągnij aby zmienić kolejność, naciśnij aby usunąć, naciśnij „+” aby dodać" rememberNoteVisibility: "Zapamiętuj ustawienia widoczności wpisu" attachCancel: "Usuń załącznik" +deleteFile: "Usuń plik" markAsSensitive: "Oznacz jako NSFW" unmarkAsSensitive: "Cofnij NSFW" enterFileName: "Wprowadź nazwę pliku" mute: "Wycisz" unmute: "Cofnij wyciszenie" +renoteMute: "Wycisz renote'y" +renoteUnmute: "Wyłącz wyciszenie renote'ów" block: "Zablokuj" unblock: "Odblokuj" suspend: "Zawieś" @@ -128,8 +147,10 @@ unblockConfirm: "Czy na pewno chcesz odblokować to konto?" suspendConfirm: "Czy na pewno chcesz zawiesić to konto?" unsuspendConfirm: "Czy na pewno chcesz cofnąć zawieszenie tego konta?" selectList: "Wybierz listę" +editList: "Edytuj listę" selectChannel: "Wybierz kanał" selectAntenna: "Wybierz Antennę" +editAntenna: "Edytuj antenę" selectWidget: "Wybierz widżet" editWidgets: "Edytuj widżety" editWidgetsExit: "Gotowe" @@ -142,11 +163,15 @@ addEmoji: "Dodaj emoji" settingGuide: "Proponowana konfiguracja" cacheRemoteFiles: "Przechowuj zdalne pliki w pamięci podręcznej" cacheRemoteFilesDescription: "Gdy ta opcja jest wyłączona, zdalne pliki są ładowane bezpośrednio ze zdalnych instancji. Wyłączenie the opcji zmniejszy użycie powierzchni dyskowej, ale zwiększy transfer, ponieważ miniaturki nie będą generowane." +youCanCleanRemoteFilesCache: "Możesz wyczyścić cache poprzez kliknięcie przycisku 🗑️ w widoku menedżera plików." +cacheRemoteSensitiveFiles: "Przechowuj wrażliwe zdalne pliki w pamięci podręcznej" +cacheRemoteSensitiveFilesDescription: "Gdy ta opcja jest wyłączona, wrażliwe pliki zdalne są wczytywane bezpośrednio ze zdalnej instancji bez cacheowania." flagAsBot: "To konto jest botem" flagAsBotDescription: "Jeżeli ten kanał jest kontrolowany przez jakiś program, ustaw tę opcję. Jeżeli włączona, będzie działać jako flaga informująca innych programistów, aby zapobiegać nieskończonej interakcji z różnymi botami i dostosowywać wewnętrzne systemy Misskey, traktując konto jako bota." flagAsCat: "To konto jest kotem" flagAsCatDescription: "Przełącz tę opcję, aby konto było oznaczone jako kot." flagShowTimelineReplies: "Pokazuj odpowiedzi na osi czasu" +flagShowTimelineRepliesDescription: "Gdy włączone, pokazuje odpowiedzi użytkowników na notatki innych użytkowników w osi czasu." autoAcceptFollowed: "Automatycznie przyjmuj prośby o możliwość obserwacji od użytkowników, których obserwujesz" addAccount: "Dodaj konto" reloadAccountsList: "Odśwież listę kont" @@ -176,6 +201,7 @@ perHour: "co godzinę" perDay: "co dzień" stopActivityDelivery: "Przestań przesyłać aktywności" blockThisInstance: "Zablokuj tę instancję" +silenceThisInstance: "Wycisz tę instancję" operations: "Działania" software: "Oprogramowanie" version: "Wersja" @@ -195,6 +221,8 @@ clearCachedFiles: "Wyczyść pamięć podręczną" clearCachedFilesConfirm: "Czy na pewno chcesz usunąć wszystkie zdalne pliki z pamięci podręcznej?" blockedInstances: "Zablokowane instancje" blockedInstancesDescription: "Wypisz nazwy hostów instancji, które powinny zostać zablokowane. Wypisane instancje nie będą mogły dłużej komunikować się z tą instancją." +silencedInstances: "Wyciszone instancje" +silencedInstancesDescription: "Wypisz nazwy hostów instancji, które chcesz wyciszyć. Wszystkie konta wymienionych instancji będą traktowane jako wyciszone, będą mogły jedynie wysyłać prośby o obserwację i nie będą mogły wspominać kont lokalnych, jeśli nie będą obserwowane. Nie będzie to miało wpływu na zablokowane instancje." muteAndBlock: "Wycisz / Zablokuj" mutedUsers: "Wyciszeni użytkownicy" blockedUsers: "Zablokowani użytkownicy" @@ -239,10 +267,12 @@ removed: "Pomyślnie usunięto" removeAreYouSure: "Czy na pewno chcesz usunąć „{x}”?" deleteAreYouSure: "Czy na pewno chcesz usunąć „{x}”?" resetAreYouSure: "Czy na pewno chcesz zresetować?" +areYouSure: "Na pewno?" saved: "Zapisano" messaging: "Wiadomości" upload: "Wyślij" keepOriginalUploading: "Zachowaj oryginalny obraz" +keepOriginalUploadingDescription: "Zapisuje oryginalnie przesłany obraz w niezmienionej postaci. Jeśli ta opcja jest wyłączona, po przesłaniu zostanie wygenerowana wersja do wyświetlenia w Internecie." fromDrive: "Z dysku" fromUrl: "Z adresu URL" uploadFromUrl: "Wyślij z adresu URL" @@ -255,7 +285,10 @@ noMoreHistory: "Nie ma dalszej historii" startMessaging: "Rozpocznij czat" nUsersRead: "przeczytano przez {n}" agreeTo: "Wyrażam zgodę na {0}" +agree: "Zatwierdź" agreeBelow: "Zaakceptuj poniżej" +basicNotesBeforeCreateAccount: "Ważne notatki" +termsOfService: "Warunki usługi" start: "Rozpocznij" home: "Strona główna" remoteUserCaution: "Te informacje mogą nie być aktualne, ponieważ użytkownik pochodzi ze zdalnej instancji." @@ -285,6 +318,7 @@ folderName: "Nazwa katalogu" createFolder: "Utwórz katalog" renameFolder: "Zmień nazwę katalogu" deleteFolder: "Usuń ten katalog" +folder: "Folder" addFile: "Dodaj plik" emptyDrive: "Dysk jest pusty" emptyFolder: "Ten katalog jest pusty" @@ -298,6 +332,7 @@ copyUrl: "Skopiuj adres URL" rename: "Zmień nazwę" avatar: "Awatar" banner: "Baner" +displayOfSensitiveMedia: "Wyświetlanie wrażliwej zawartości" whenServerDisconnected: "Po utracie połączenia z serwerem" disconnectedFromServer: "Utracono połączenie z serwerem." reload: "Odśwież" @@ -345,8 +380,11 @@ hcaptcha: "hCaptcha" enableHcaptcha: "Włącz hCaptcha" hcaptchaSiteKey: "Klucz strony" hcaptchaSecretKey: "Tajny klucz" +mcaptcha: "mCaptcha" +enableMcaptcha: "Włącz mCaptcha" mcaptchaSiteKey: "Klucz strony" mcaptchaSecretKey: "Tajny klucz" +mcaptchaInstanceUrl: "URL instancji mCaptcha" recaptcha: "reCAPTCHA" enableRecaptcha: "Włącz reCAPTCHA" recaptchaSiteKey: "Klucz strony" @@ -389,15 +427,19 @@ aboutMisskey: "O Misskey" administrator: "Admin" token: "Token" 2fa: "Klucz 2FA " +setupOf2fa: "Skonfiguruj dwuetapową autentykację" totp: "Klucz aplikacji uwierzytelniającej (totp)" totpDescription: "Opis klucza czasowego" moderator: "Moderator" moderation: "Moderacja" +moderationNote: "Notka moderacyjna" +addModerationNote: "Dodaj notkę moderacyjną" +moderationLogs: "Logi moderacyjne" nUsersMentioned: "{n} wspomnianych użytkowników" securityKeyAndPasskey: "Klucz bezpieczeństwa i klucze Passkey" securityKey: "Klucz bezpieczeństwa" lastUsed: "Ostatnio używane" -lastUsedAt: "Ostatnio używane w" +lastUsedAt: "Ostatnio używane: {t}" unregister: "Cofnij rejestrację" passwordLessLogin: "Skonfiguruj logowanie bez użycia hasła" passwordLessLoginDescription: "Opis logowania bez użycia hasła" @@ -451,8 +493,12 @@ aboutX: "O {x}" emojiStyle: "Styl emoji" native: "Natywny" disableDrawer: "Nie używaj menu w stylu szuflady" +showNoteActionsOnlyHover: "Pokazuj akcje notatek tylko po najechaniu myszką" +showReactionsCount: "Wyświetl liczbę reakcji na notatkę" noHistory: "Brak historii" signinHistory: "Historia logowania" +enableAdvancedMfm: "Włącz zaawansowane MFM" +enableAnimatedMfm: "Włącz animowane MFM" doing: "Przetwarzanie..." category: "Kategoria" tags: "Tagi" @@ -461,6 +507,8 @@ createAccount: "Utwórz konto" existingAccount: "Istniejące konto" regenerate: "Wygeneruj ponownie" fontSize: "Rozmiar czcionki" +mediaListWithOneImageAppearance: "Wysokość list multimediów z tylko jednym obrazem" +limitTo: "Limituj do {x}" noFollowRequests: "Nie masz żadnych oczekujących próśb o możliwość obserwacji" openImageInNewTab: "Otwórz obraz w nowej karcie" dashboard: "Kokpit" @@ -480,6 +528,7 @@ showFeaturedNotesInTimeline: "Pokazuj wyróżnione wpisy w osi czasu" objectStorage: "Pamięć obiektowa" useObjectStorage: "Używaj pamięci obiektowej" objectStorageBaseUrl: "Podstawowy URL" +objectStorageBaseUrlDesc: "Adres URL używany jako odniesienie. Podaj adres URL swojego CDN lub Proxy, gdy używasz któregokolwiek z nich.\nDla S3 użyj 'https://.s3.amazonaws.com' a dla GCS lub równej usługi użyj 'https://storage.googleapis.com/', itd." objectStorageBucket: "Bucket" objectStorageBucketDesc: "Podaj nazwę „wiadra” używaną przez konfigurowaną usługę." objectStoragePrefix: "Prefiks" @@ -492,9 +541,13 @@ objectStorageUseSSL: "Użyj SSL" objectStorageUseSSLDesc: "Wyłącz, jeżeli nie zamierzasz używać HTTPS dla połączenia z API" objectStorageUseProxy: "Połącz przez proxy" objectStorageUseProxyDesc: "Wyłącz, jeżeli nie zamierzasz używać proxy dla połączenia z pamięcią blokową" +objectStorageSetPublicRead: "Ustaw opcję \"public-read\" przy przesyłaniu" +s3ForcePathStyleDesc: "Jeśli opcja s3ForcePathStyle jest włączona, nazwa Bucket'u musi być zawarta w ścieżce adresu URL, a nie w nazwie hosta adresu URL. Włączenie tego ustawienia może być konieczne w przypadku użycia usług takich jak self-hosted instancja Minio." serverLogs: "Dziennik zdarzeń" deleteAll: "Usuń wszystkie" showFixedPostForm: "Wyświetlaj formularz tworzenia wpisu w górnej części osi czasu" +showFixedPostFormInChannel: "Wyświetl formularz postowania w górnej części osi czasu (Kanały)" +withRepliesByDefaultForNewlyFollowed: "Domyślnie uwzględnij odpowiedzi nowo obserwowanych użytkowników w osi czasu" newNoteRecived: "Masz nowy wpis" sounds: "Dźwięk" sound: "Dźwięki" @@ -504,6 +557,8 @@ showInPage: "Pokaż na stronie" popout: "Popout" volume: "Głośność" masterVolume: "Głośność główna" +notUseSound: "Wyłącz dźwięk" +useSoundOnlyWhenActive: "Puszczaj dźwięki tylko, gdy Misskey jest aktywne." details: "Szczegóły" chooseEmoji: "Wybierz emoji" unableToProcess: "Nie udało się dokończyć działania." @@ -524,6 +579,10 @@ output: "Wyjście" script: "Skrypt" disablePagesScript: "Wyłącz AiScript na Stronach" updateRemoteUser: "Aktualizuj zdalne dane o użytkowniku" +unsetUserAvatar: "Usuń awatar" +unsetUserAvatarConfirm: "Czy na pewno chcesz usunąć awatar tego użytkownika?" +unsetUserBanner: "Usuń baner" +unsetUserBannerConfirm: "Czy na pewno chcesz usunąć baner?" deleteAllFiles: "Usuń wszystkie pliki" deleteAllFilesConfirm: "Czy na pewno chcesz usunąć wszystkie pliki?" removeAllFollowing: "Przestań obserwować" @@ -539,6 +598,7 @@ accountDeletedDescription: "Opis konta usuniętego" menu: "Menu" divider: "Rozdzielacz" addItem: "Dodaj element" +rearrange: "Posortuj" relays: "Przekaźniki" addRelay: "Dodaj przekaźnik" inboxUrl: "Adres URL skrzynki nadawczej" @@ -573,6 +633,7 @@ medium: "Średnie" small: "Małe" generateAccessToken: "Generuj token dostępu" permission: "Uprawnienia" +adminPermission: "Uprawnienia administracyjne" enableAll: "Włącz wszystko" disableAll: "Wyłącz wszystko" tokenRequested: "Przydziel dostęp do konta" @@ -590,9 +651,12 @@ smtpPort: "Port" smtpUser: "Nazwa użytkownika" smtpPass: "Hasło" emptyToDisableSmtpAuth: "Pozostaw adres e-mail i hasło puste, aby wyłączyć weryfikację SMTP" +smtpSecure: "Użyj niejawnego SSL/TLS dla połączeń SMTP" smtpSecureInfo: "Wyłącz, jeżeli używasz STARTTLS" testEmail: "Przetestuj dostarczanie wiadomości e-mail" wordMute: "Wyciszenie słowa" +regexpError: "Błąd wyrażenia regularnego" +regexpErrorDescription: "Wystąpił błąd w wyrażeniu regularnym w linii {line} twoich {tab} wyciszeń:" instanceMute: "Wyciszone instancje" userSaysSomething: "{name} powiedział(-a) coś" makeActive: "Aktywuj" @@ -612,18 +676,22 @@ useGlobalSettingDesc: "Jeżeli włączone, zostaną wykorzystane ustawienia powi other: "Inne" regenerateLoginToken: "Generuj token logowania ponownie" regenerateLoginTokenDescription: "Regeneruje token używany wewnętrznie podczas logowania. Zazwyczaj nie jest to konieczne. Po regeneracji wszystkie urządzenia zostaną wylogowane." +theKeywordWhenSearchingForCustomEmoji: "To jest słowo kluczowe używane podczas wyszukiwania customowych Emoji." setMultipleBySeparatingWithSpace: "Możesz ustawić wiele, oddzielając je spacjami." fileIdOrUrl: "ID pliku albo URL" behavior: "Zachowanie" sample: "Przykład" abuseReports: "Zgłoszenia" reportAbuse: "Zgłoś" +reportAbuseRenote: "Zgłoś renote" reportAbuseOf: "Zgłoś {name}" fillAbuseReportDescription: "Wypełnij szczegóły zgłoszenia. Jeżeli dotyczy ono określonego wpisu, uwzględnij jego adres URL." abuseReported: "Twoje zgłoszenie zostało wysłane. Dziękujemy." +reporter: "Zgłaszający" reporteeOrigin: "Pochodzenie zgłoszonego" reporterOrigin: "Pochodzenie zgłaszającego" forwardReport: "Przekaż zgłoszenie do innej instancji" +forwardReportIsAnonymous: "Zamiast twojego konta, anonimowe konto systemowe będzie wyświetlone jako zgłaszający na instancji zdalnej." send: "Wyślij" abuseMarkAsResolved: "Oznacz zgłoszenie jako rozwiązane" openInNewTab: "Otwórz w nowej karcie" @@ -668,6 +736,7 @@ lockedAccountInfo: "Dopóki nie ustawisz widoczności wpisu na \"Obserwujący\", alwaysMarkSensitive: "Oznacz domyślnie jako NSFW" loadRawImages: "Wyświetlaj zdjęcia w załącznikach w całości zamiast miniatur" disableShowingAnimatedImages: "Nie odtwarzaj animowanych obrazów" +highlightSensitiveMedia: "Podkreśl wrażliwą zawartość" verificationEmailSent: "Wiadomość weryfikacyjna została wysłana. Odwiedź uwzględniony odnośnik, aby ukończyć weryfikację." notSet: "Nie ustawiono" emailVerified: "Adres e-mail został potwierdzony" @@ -678,6 +747,8 @@ contact: "Kontakt" useSystemFont: "Używaj domyślnej czcionki systemu" clips: "Klipy" experimentalFeatures: "Eksperymentalne funkcje" +experimental: "Eksperymentalne" +thisIsExperimentalFeature: "Ta funkcja jest eksperymentalna. Jej funkcjonalność może ulec zmianie, i może ona nie funkcjonować tak, jak zamierzono." developer: "Programista" makeExplorable: "Pokazuj konto na stronie „Eksploruj”" makeExplorableDescription: "Jeżeli wyłączysz tę opcję, Twoje konto nie będzie wyświetlać się w sekcji „Eksploruj”." @@ -695,12 +766,14 @@ onlineUsersCount: "{n} osób jest online" nUsers: "{n} użytkowników" nNotes: "{n} wpisów" sendErrorReports: "Wyślij raporty o błędach" +sendErrorReportsDescription: "Gdy włączone, jeśli wystąpi problem, szczegółowe informacje o błędach będą udostępniane Misskey, pomagając ulepszyć jakość Misskey.\nBędzie to zawierało informacje takie jak wersja twojego systemu operacyjnego, jakiej przeglądarki używasz, twoja aktywność w Misskey, itd." myTheme: "Mój motyw" backgroundColor: "Tło" accentColor: "Akcent" textColor: "Tekst" saveAs: "Zapisz jako…" advanced: "Zaawansowane" +advancedSettings: "Zaawansowane ustawienia" value: "Wartość" createdAt: "Utworzono" updatedAt: "Zaktualizowano" @@ -760,12 +833,14 @@ noMaintainerInformationWarning: "Informacje o administratorze nie są skonfiguro noBotProtectionWarning: "Zabezpieczenie przed botami nie jest skonfigurowane." configure: "Skonfiguruj" postToGallery: "Opublikuj w galerii" +postToHashtag: "Postuj do tego hashtagu" gallery: "Galeria" recentPosts: "Ostatnie wpisy" popularPosts: "Popularne wpisy" shareWithNote: "Udostępnij z wpisem" ads: "Reklamy" expiration: "Ankieta kończy się" +startingperiod: "Początek" memo: "Notatki" priority: "Priorytet" high: "Wysoki" @@ -792,13 +867,19 @@ translatedFrom: "Przetłumaczone z {x}" accountDeletionInProgress: "Trwa usuwanie konta" usernameInfo: "Nazwa, która identyfikuje Twoje konto spośród innych na tym serwerze. Możesz użyć alfabetu (a~z, A~Z), cyfr (0~9) lub podkreślników (_). Nazwy użytkownika nie mogą być później zmieniane." aiChanMode: "Tryb Ai" +devMode: "Tryb programisty" keepCw: "Zostaw ostrzeżenia o zawartości" pubSub: "Konta Pub/Sub" +lastCommunication: "Ostatnia komunikacja" resolved: "Rozwiązane" unresolved: "Nierozwiązane" breakFollow: "Usuń obserwującego" +breakFollowConfirm: "Czy na pewno usunąć tego obserwującego?" itsOn: "Włączone" itsOff: "Wyłączone" +on: "Włączone" +off: "Wyłączone" +emailRequiredForSignup: "Wymagaj adresu e-mail do rejestracji" unread: "Nieodczytane" filter: "Filtr" controlPanel: "Panel sterowania" @@ -808,6 +889,8 @@ makeReactionsPublicDescription: "To spowoduje, że lista wszystkich Twoich dotyc classic: "Klasyczny" muteThread: "Wycisz wątek" unmuteThread: "Wyłącz wyciszenie wątku" +followingVisibility: "Widoczność obserwacji" +followersVisibility: "Widoczność obserwujących" continueThread: "Pokaż kontynuację wątku" deleteAccountConfirm: "Spowoduje to nieodwracalne usunięcie Twojego konta. Kontynuować?" incorrectPassword: "Nieprawidłowe hasło." @@ -820,9 +903,14 @@ overridedDeviceKind: "Typ urządzenia" smartphone: "Smartfon" tablet: "Tablet" auto: "Automatycznie" +themeColor: "Motyw kolorystyczny" size: "Rozmiar" numberOfColumn: "Liczba kolumn" searchByGoogle: "Szukaj" +instanceDefaultLightTheme: "Domyślny motyw dla trybu jasnego" +instanceDefaultDarkTheme: "Domyślny motyw dla trybu ciemnego" +instanceDefaultThemeDescription: "Opis domyślnego motywu instancji" +mutePeriod: "Okres wyciszenia" period: "Ankieta kończy się" indefinitely: "Nigdy" tenMinutes: "10 minut" @@ -831,29 +919,50 @@ oneDay: "1 dzień" oneWeek: "1 tydzień" oneMonth: "jeden miesiąc" failedToFetchAccountInformation: "Nie udało się uzyskać informacji o koncie" +rateLimitExceeded: "Limit szybkości przekroczony" +cropImage: "Przytnij obraz" +cropImageAsk: "Czy chcesz przyciąć obrazek?" +cropYes: "Tak, przytnij" +cropNo: "Nie chce przycinać" file: "Pliki" +recentNHours: "W ciągu ostatnich {n} godzin" +recentNDays: "W ciągu ostatnich {n} dni" +noEmailServerWarning: "Serwer Email nie jest skonfigurowany" recommended: "Zalecane" check: "Zweryfikuj" +driveCapOverrideLabel: "Zmień limit pojemności dysku użytkownika" +requireAdminForView: "Aby to zobaczyć, musisz być administratorem" +isSystemAccount: "To jest konto stworzone i zarządzane przez system" +typeToConfirm: "Wprowadź {x}, aby potwierdzić" deleteAccount: "Usuń konto" document: "Dokumentacja" numberOfPageCache: "Ilość stron w cache" +numberOfPageCacheDescription: "Zwiększenie tej liczby polepszy wygodę, ale spowoduje większe obciążenie jako użycie pamięci na urządzeniu użytkownika." logoutConfirm: "Czy na pewno chcesz się wylogować?" lastActiveDate: "Ostatnio użyte w" statusbar: "Pasek stanu" pleaseSelect: "Wybierz opcję" reverse: "Odwróć" colored: "Kolorowe" +refreshInterval: "Okres aktualizacji" label: "Etykieta" type: "Typ" speed: "Prędkość" +slow: "Wolny" +fast: "Szybki" +sensitiveMediaDetection: "Detekcja wrażliwej zawartości" localOnly: "Lokalne tylko" +remoteOnly: "Tylko zdalne instancje" failedToUpload: "Przesyłanie nie powiodło się" cannotUploadBecauseInappropriate: "Nie można przesłać tego pliku, ponieważ jego części zostały wykryte jako potencjalnie nieodpowiednie." cannotUploadBecauseNoFreeSpace: "Przesyłanie nie powiodło się z powodu braku miejsca na dysku." +cannotUploadBecauseExceedsFileSizeLimit: "Nie można przesłać pliku, ponieważ wykracza on poza limit wielkości pliku." beta: "Beta" enableAutoSensitive: "Automatyczne oznaczanie NSFW" enableAutoSensitiveDescription: "Umożliwia automatyczne wykrywanie i oznaczanie zawartości NSFW za pomocą uczenia maszynowego. Nawet jeśli ta opcja jest wyłączona, może być włączona w całej instancji." +activeEmailValidationDescription: "Włącza bardziej restrykcyjną walidację adresów e-mail, co obejmuje sprawdzanie adresów jednorazowych i czy komunikacja z tym adresem jest możliwa. Gdy wyłączone, tylko format adresu e-mail jest sprawdzany." navbar: "Pasek nawigacyjny" +shuffle: "Mieszaj" account: "Konta" move: "Przenieś" pushNotification: "Powiadomienia" @@ -863,22 +972,74 @@ pushNotificationAlreadySubscribed: "Powiadomienia push są włączone" pushNotificationNotSupported: "Przeglądarka lub instancja nie obsługuje powiadomień push" sendPushNotificationReadMessage: "Usuń powiadomienia push po przeczytaniu powiadomień i wiadomości." sendPushNotificationReadMessageCaption: "Chwilowo pojawi się powiadomienie \"{emptyPushNotificationMessage}\". Może wzrosnąć zużycie baterii urządzenia." +windowMaximize: "Maksymalizuj" +windowMinimize: "Minimalizuj" +windowRestore: "Przywróć" +caption: "Legenda" loggedInAsBot: "Jesteś obecnie zalogowany/a jako bot" +tools: "Narzędzia" +cannotLoad: "Nie można wczytać" +numberOfProfileView: "Wyświetlenia profilu" like: "Polub" +unlike: "Usuń polubienie" +numberOfLikes: "Liczba polubień" show: "Wyświetlanie" +neverShow: "Nie pokazuj ponownie" +remindMeLater: "Przypomnij później" +didYouLikeMisskey: "Czy Misskey się tobie spodobało?" +pleaseDonate: "{host} używa darmowego oprogramowania — Misskey. Bylibyśmy bardzo wdzięczni za datki, które pozwolą na kontynuację rozwoju Misskey!" +correspondingSourceIsAvailable: "Odpowiedni kod źródłowy jest dostępny pod {anchor}." +roles: "Role" +role: "Rola" +noRole: "Rola nie znaleziona" +normalUser: "Normalny użytkownik" +undefined: "Niezdefiniowane" +assign: "Przydziel" +unassign: "Cofnij przydzielenie" color: "Kolor" +manageCustomEmojis: "Zarządzaj niestandardowymi Emoji" +manageAvatarDecorations: "Zarządzaj dekoracjami awatara" +invalidParamError: "Błąd parametrów" +permissionDeniedError: "Odrzucono operacje" +permissionDeniedErrorDescription: "Konto nie posiada uprawnień" +preset: "Konfiguracja" +selectFromPresets: "Wybierz konfiguracje" +achievements: "Osiągnięcia" +thisPostMayBeAnnoyingCancel: "Odrzuć" +internalServerError: "Wewnętrzny błąd serwera" +internalServerErrorDescription: "Niespodziewany błąd po stronie serwera" +copyErrorInfo: "Kopiuj informacje o błędzie" +joinThisServer: "Dołącz do chaty" +disableFederationOk: "Wyłącz federacje" +invitationRequiredToRegister: "Ten serwer wymaga zaproszenia. Tylko osoby z zaproszeniem mogą się zarejestrować" +emailNotSupported: "Wysyłanie wiadomości E-mail nie jest obsługiwane na tym serwerze" +postToTheChannel: "Publikuj na kanale" youFollowing: "Śledzeni" icon: "Awatar" replies: "Odpowiedzi" renotes: "Udostępnień" sourceCode: "Kod źródłowy" flip: "Odwróć" +lastNDays: "W ciągu ostatnich {n} dni" +surrender: "Odrzuć" +gameRetry: "Spróbuj ponownie" +_delivery: + stop: "Zawieszono" + _type: + none: "Publikowanie" +_bubbleGame: + _score: + score: "Wynik" _role: + assignTarget: "Przydziel" priority: "Priorytet" _priority: low: "Niski" middle: "Średnie" high: "Wysoki" + _options: + canManageCustomEmojis: "Zarządzaj niestandardowymi Emoji" + canManageAvatarDecorations: "Zarządzaj dekoracjami awatara" _sensitiveMediaDetection: description: "Zmniejsza wysiłek związany z moderacją serwera dzięki automatycznemu rozpoznawaniu zawartości NSFW za pomocą uczenia maszynowego. To nieznacznie zwiększy obciążenie serwera." setSensitiveFlagAutomatically: "Oznacz jako NSFW" diff --git a/locales/pt-PT.yml b/locales/pt-PT.yml index 26657e7b52..0bfd1f778b 100644 --- a/locales/pt-PT.yml +++ b/locales/pt-PT.yml @@ -733,9 +733,9 @@ reloadToApplySetting: "As configurações serão refletidas após recarregar a p needReloadToApply: "É necessário recarregar a página para refletir as alterações." showTitlebar: "Exibir barra de título" clearCache: "Limpar o cache" -onlineUsersCount: "Pessoas Online" -nUsers: "Usuários" -nNotes: "Notas" +onlineUsersCount: "{n} Pessoas Online" +nUsers: "{n} Usuários" +nNotes: "{n} Notas" sendErrorReports: "Enviar relatórios de erro" sendErrorReportsDescription: "Ao ativar essa opção, informações detalhadas de erro serão compartilhadas com o Misskey em caso de problemas, o que pode ajudar a melhorar a qualidade do software. As informações de erro podem incluir a versão do sistema operacional, o tipo de navegador e o sua atividade no Misskey." myTheme: "Meu tema" @@ -767,7 +767,7 @@ emailNotification: "Notificações por e-mail" publish: "Publicar" inChannelSearch: "Pesquisar no canal" useReactionPickerForContextMenu: "Clique com o botão direito do mouse para abrir o seletor de reações." -typingUsers: "digitando" +typingUsers: "{users} pessoas digitando" jumpToSpecifiedDate: "Pular para uma data específica" showingPastTimeline: "Visualizar linha de tempo anterior" clear: "Limpar" @@ -834,7 +834,7 @@ learnMore: "Saiba mais" misskeyUpdated: "Misskey foi atualizado!" whatIsNew: "Ver atualizações" translate: "Traduzir" -translatedFrom: "Traduzido de" +translatedFrom: "Traduzido de {x}" accountDeletionInProgress: "Encerramento de conta em andamento" usernameInfo: "O nome para identificar exclusivamente a sua conta no servidor. Pode conter letras (az, AZ), números (0~9) e sublinhados (_). O nome de usuário não pode ser alterado posteriormente." aiChanMode: "Modo AI-chan" @@ -1012,6 +1012,10 @@ keepScreenOn: "Manter a tela do dispositivo sempre ligada" flip: "Inversão" lastNDays: "Últimos {n} dias" surrender: "Cancelar" +_delivery: + stop: "Suspenso" + _type: + none: "Publicando" _initialAccountSetting: followUsers: "Siga usuários que lhe interessam para criar a sua linha do tempo." _serverSettings: @@ -1301,8 +1305,8 @@ _preferencesBackups: _channel: featured: "Destaques" following: "Seguindo" - usersCount: "usuários ativos" - notesCount: "notas" + usersCount: "{n} usuários ativos" + notesCount: "{n} notas" nameAndDescription: "Nome e descrição" _menuDisplay: sideFull: "Exibir painel lateral inteiro" @@ -1501,4 +1505,3 @@ _moderationLogTypes: resetPassword: "Redefinir senha" _reversi: total: "Total" - diff --git a/locales/ro-RO.yml b/locales/ro-RO.yml index e45b8b75ec..88424cbbfb 100644 --- a/locales/ro-RO.yml +++ b/locales/ro-RO.yml @@ -651,6 +651,10 @@ show: "Arată" icon: "Avatar" replies: "Răspunsuri" renotes: "Re-notează" +_delivery: + stop: "Suspendat" + _type: + none: "Publicare" _role: _priority: middle: "Mediu" @@ -729,4 +733,3 @@ _moderationLogTypes: resetPassword: "Resetează parola" _reversi: total: "Total" - diff --git a/locales/ru-RU.yml b/locales/ru-RU.yml index d666b69490..71f5cad601 100644 --- a/locales/ru-RU.yml +++ b/locales/ru-RU.yml @@ -17,7 +17,7 @@ noThankYou: "Нет, спасибо" enterUsername: "Введите имя пользователя" renotedBy: "{user} делится" noNotes: "Нет ни одной заметки" -noNotifications: "Нет ни одного уведомления" +noNotifications: "Нет уведомлений" instance: "Инстанс" settings: "Настройки" notificationSettings: "Настройки уведомлений" @@ -129,6 +129,7 @@ overwriteFromPinnedEmojis: "Заменить на эмодзи из общего reactionSettingDescription2: "Расставляйте перетаскиванием, удаляйте нажатием, добавляйте кнопкой «+»." rememberNoteVisibility: "Запоминать видимость заметок" attachCancel: "Удалить вложение" +deleteFile: "Удалить файл" markAsSensitive: "Отметить как «не для всех»" unmarkAsSensitive: "Снять отметку «не для всех»" enterFileName: "Введите имя файла" @@ -312,6 +313,7 @@ folderName: "Имя папки" createFolder: "Создать папку" renameFolder: "Переименовать папку" deleteFolder: "Удалить папку" +folder: "Папка" addFile: "Добавить файл" emptyDrive: "Диск пуст" emptyFolder: "Папка пуста" @@ -373,6 +375,8 @@ hcaptcha: "hCaptcha" enableHcaptcha: "Включить hCaptcha" hcaptchaSiteKey: "Ключ сайта" hcaptchaSecretKey: "Секретный ключ" +mcaptcha: "mCaptcha" +enableMcaptcha: "Включить mCaptcha" mcaptchaSiteKey: "Ключ сайта" mcaptchaSecretKey: "Секретный ключ" recaptcha: "reCAPTCHA" @@ -542,6 +546,8 @@ showInPage: "Показать страницу" popout: "Развернуть" volume: "Громкость" masterVolume: "Основная регулировка громкости" +notUseSound: "Выключить звук" +useSoundOnlyWhenActive: "Использовать звук, когда Misskey активен." details: "Подробнее" chooseEmoji: "Выберите эмодзи" unableToProcess: "Не удаётся завершить операцию" @@ -562,6 +568,10 @@ output: "Выходы" script: "Скрипт" disablePagesScript: "Отключить скрипты на «Страницах»" updateRemoteUser: "Обновить данные пользователя с его сервера" +unsetUserAvatar: "Убрать аватар" +unsetUserAvatarConfirm: "Вы точно хотите убрать аватар?" +unsetUserBanner: "Убрать баннер" +unsetUserBannerConfirm: "Вы точно хотите убрать баннер?" deleteAllFiles: "Удалить все файлы" deleteAllFilesConfirm: "Вы хотите удалить все файлы?" removeAllFollowing: "Удалить всех подписчиков" @@ -612,6 +622,7 @@ medium: "Средне" small: "Мелко" generateAccessToken: "Создать токен доступа" permission: "Разрешения" +adminPermission: "Доступ администратора" enableAll: "Включить все" disableAll: "Выключить всё" tokenRequested: "Открыть доступ к учётной записи" @@ -633,6 +644,7 @@ smtpSecure: "Использовать SSL/TLS для SMTP-соединений" smtpSecureInfo: "Выключите при использовании STARTTLS." testEmail: "Проверка доставки электронной почты" wordMute: "Скрытие слов" +hardWordMute: "" regexpError: "Ошибка в регулярном выражении" regexpErrorDescription: "В списке {tab} скрытых слов, в строке {line} обнаружена синтаксическая ошибка:" instanceMute: "Глушение инстансов" @@ -1084,8 +1096,13 @@ renotes: "Репост" loadReplies: "Показать ответы" sourceCode: "Исходный код" flip: "Переворот" +code: "Код" lastNDays: "Последние {n} сут" surrender: "Этот пост не может быть отменен." +_delivery: + stop: "Заморожено" + _type: + none: "Публикация" _initialAccountSetting: accountCreated: "Аккаунт успешно создан!" letsStartAccountSetup: "Давайте настроим вашу учётную запись." @@ -1626,7 +1643,6 @@ _2fa: registerTOTP: "Начните настраивать приложение-аутентификатор" step1: "Прежде всего, установите на устройство приложение для аутентификации, например, {a} или {b}." step2: "Далее отсканируйте отображаемый QR-код при помощи приложения." - step2Click: "Нажав на QR-код, вы можете зарегистрироваться с помощью приложения для аутентификации или брелка для ключей, установленного на вашем устройстве." step3Title: "Введите проверочный код" step3: "И наконец, введите код, который покажет приложение." step4: "Теперь при каждом входе на сайт вам нужно будет вводить код из приложения аналогичным образом." @@ -1975,4 +1991,3 @@ _moderationLogTypes: resetPassword: "Сброс пароля:" _reversi: total: "Всего" - diff --git a/locales/si-LK.yml b/locales/si-LK.yml index cd21505a47..e130d68ed8 100644 --- a/locales/si-LK.yml +++ b/locales/si-LK.yml @@ -1,2 +1,19 @@ --- - +_lang_: "සිංහල" +monthAndDay: "{month}-{day}" +username: "පරිශීලක නාමය" +password: "මුරපදය" +cancel: "අවලංගු කරන්න" +instance: "සර්වර්" +login: "පිවිසෙන්න" +users: "පරිශීලක" +note: "නෝට්" +notes: "නෝට්" +instances: "සර්වර්" +smtpUser: "පරිශීලක නාමය" +smtpPass: "මුරපදය" +user: "පරිශීලක" +_sfx: + note: "නෝට්" +_profile: + username: "පරිශීලක නාමය" diff --git a/locales/sk-SK.yml b/locales/sk-SK.yml index f280f91270..6ae90395ab 100644 --- a/locales/sk-SK.yml +++ b/locales/sk-SK.yml @@ -922,6 +922,10 @@ renotes: "Preposlať" sourceCode: "Zdrojový kód" flip: "Preklopiť" lastNDays: "Posledných {n} dní" +_delivery: + stop: "Zmrazené" + _type: + none: "Zverejňovanie" _role: priority: "Priorita" _priority: @@ -1448,4 +1452,3 @@ _moderationLogTypes: resetPassword: "Resetovať heslo" _reversi: total: "Celkom" - diff --git a/locales/sv-SE.yml b/locales/sv-SE.yml index 76b9bc90b7..11b2b36499 100644 --- a/locales/sv-SE.yml +++ b/locales/sv-SE.yml @@ -488,6 +488,10 @@ dataSaver: "Databesparing" icon: "Profilbild" replies: "Svar" renotes: "Omnotera" +_delivery: + stop: "Suspenderad" + _type: + none: "Publiceras" _achievements: _types: _open3windows: @@ -576,4 +580,3 @@ _webhookSettings: _moderationLogTypes: suspend: "Suspendera" resetPassword: "Återställ Lösenord" - diff --git a/locales/th-TH.yml b/locales/th-TH.yml index f0ddeab822..01510cc03c 100644 --- a/locales/th-TH.yml +++ b/locales/th-TH.yml @@ -33,7 +33,7 @@ logout: "ออกจากระบบ" signup: "สร้างบัญชีผู้ใช้" uploading: "กำลังอัปโหลด" save: "บันทึก" -users: "ผู้ใช้งาน" +users: "ผู้ใช้" addUser: "เพิ่มผู้ใช้" favorite: "รายการโปรด" favorites: "รายการโปรด" @@ -400,6 +400,7 @@ name: "ชื่อ" antennaSource: "แหล่งเสาอากาศ" antennaKeywords: "คีย์เวิร์ดที่ควรฟัง" antennaExcludeKeywords: "คีย์เวิร์ดที่จะยกเว้น" +antennaExcludeBots: "ยกเว้นบัญชีบอต" antennaKeywordsDescription: "คั่นด้วยช่องว่างสำหรับเงื่อนไข AND หรือด้วยการขึ้นบรรทัดใหม่สำหรับเงื่อนไข OR" notifyAntenna: "แจ้งเตือนเกี่ยวกับโน้ตใหม่" withFileAntenna: "เฉพาะโน้ตที่มีไฟล์" @@ -494,6 +495,7 @@ emojiStyle: "สไตล์เอโมจิ" native: "ภาษาแม่" disableDrawer: "อย่าใช้ลิ้นชักสไตล์เมนู" showNoteActionsOnlyHover: "แสดงการดำเนินการเฉพาะโน้ตเมื่อโฮเวอร์" +showReactionsCount: "แสดงจำนวนรีแอกชั่นในโน้ต" noHistory: "ไม่มีประวัติ" signinHistory: "ประวัติการเข้าสู่ระบบ" enableAdvancedMfm: "เปิดใช้งาน MFM ขั้นสูง" @@ -825,7 +827,7 @@ switchAccount: "สลับบัญชีผู้ใช้" enabled: "เปิดใช้งาน" disabled: "ปิดการใช้งาน" quickAction: "ปุ่มลัด" -user: "ผู้ใช้งาน" +user: "ผู้ใช้" administration: "การจัดการ" accounts: "บัญชีผู้ใช้" switch: "สลับ" @@ -1223,6 +1225,20 @@ enableHorizontalSwipe: "ปัดเพื่อสลับแท็บ" loading: "กำลังโหลด" surrender: "ยอมแพ้" gameRetry: "เริ่มเกมใหม่" +notUsePleaseLeaveBlank: "หากไม่ได้ใช้กรุณาเว้นว่างไว้" +useTotp: "ใช้รหัสผ่านแบบใช้ครั้งเดียว (TOTP)" +useBackupCode: "ใช้รหัสสำรอง" +launchApp: "เริ่มแอป" +useNativeUIForVideoAudioPlayer: "ใช้ UI ของเบราว์เซอร์เพื่อเล่นวิดีโอ/เสียง" +keepOriginalFilename: "คงชื่อไฟล์เดิมไว้" +keepOriginalFilenameDescription: "หากปิดการตั้งค่านี้ ในระหว่างการอัปโหลดชื่อไฟล์จะถูกแทนที่ด้วยสตริงแบบสุ่มโดยอัตโนมัติ" +noDescription: "ไม่มีข้อความอธิบาย" +alwaysConfirmFollow: "แสดงข้อความยืนยันเมื่อกดติดตาม" +inquiry: "ติดต่อเรา" +_delivery: + stop: "ถูกระงับ" + _type: + none: "กำลังเผยแพร่" _bubbleGame: howToPlay: "วิธีเล่น" hold: "หยุดชั่วคราว" @@ -1351,7 +1367,7 @@ _serverSettings: _accountMigration: moveFrom: "ย้ายข้อมูลบัญชีอื่นไปยังอีกบัญชีนี้หนึ่ง" moveFromSub: "สร้างนามแฝงไปยังบัญชีอื่น" - moveFromLabel: "บัญชีที่จะย้ายจาก:" + moveFromLabel: "บัญชีที่จะย้ายจาก #{n}" moveFromDescription: "ถ้าหากคุณต้องการโอนข้อมูล คุณจำเป็นต้องสร้างบัญชีสำรองสำหรับการย้ายบัญชี หลังจากนั้นป้อนบัญชีที่จะย้ายไปในรูปแบบต่อไปนี้: @person@instance.com" moveTo: "ย้ายข้อมูลบัญชีนี้ไปยังบัญชีอีกหนึ่ง" moveToLabel: "บัญชีที่จะย้ายไปที่:" @@ -1682,6 +1698,11 @@ _role: roleAssignedTo: "มอบหมายให้มีบทบาทแบบทำมือ" isLocal: "ผู้ใช้ในพื้นที่" isRemote: "ผู้ใช้ระยะไกล" + isCat: "ผู้ใช้ที่เป็นแมว" + isBot: "ผู้ใช้ที่เป็นบอต" + isSuspended: "ผู้ใช้ที่ถูกระงับ" + isLocked: "ผู้ใช้บัญชีไม่เปิดเผยสาธารณะ" + isExplorable: "ผู้ใช้ที่เปิดใช้งาน “ทำให้บัญชีของฉันค้นหาได้ง่ายขึ้น”" createdLessThan: "สร้างน้อยกว่า" createdMoreThan: "สร้างมากกว่า" followersLessThanOrEq: "จำนวนผู้ติดตามน้อยกว่าหรือเท่ากับ\n" @@ -1751,6 +1772,7 @@ _plugin: installWarn: "กรุณาอย่าติดตั้งปลั๊กอินที่ไม่น่าเชื่อถือนะคะ" manage: "จัดการปลั๊กอิน" viewSource: "ดูต้นฉบับ" + viewLog: "แสดงปูม" _preferencesBackups: list: "สร้างการสำรองข้อมูล" saveNew: "บันทึกข้อมูลสำรองใหม่" @@ -1940,7 +1962,6 @@ _2fa: registerTOTP: "ลงทะเบียนแอพตัวตรวจสอบสิทธิ์" step1: "ขั้นตอนแรก ติดตั้งแอปยืนยันตัวตน (เช่น {a} หรือ {b}) บนอุปกรณ์ของคุณ" step2: "จากนั้นสแกนรหัส QR ที่แสดงบนหน้าจอนี้" - step2Click: "การคลิกที่รหัส QR นี้จะช่วยให้คุณนั้นสามารถลงทะเบียน 2FA กับคีย์ความปลอดภัยหรือแอปตรวจสอบความถูกต้องของโทรศัพท์ได้" step2Uri: "ป้อนใส่ URL ดังต่อไปนี้ถ้าหากคุณใช้โปรแกรมเดสก์ท็อป" step3Title: "ป้อนรหัสยืนยัน" step3: "ป้อนโทเค็นที่แอปของคุณให้มาเพื่อเสร็จสิ้นการตั้งค่า" @@ -1964,6 +1985,7 @@ _2fa: backupCodesDescription: "หากแอปยืนยันตัวตนของคุณไม่พร้อมใช้งาน คุณสามารถใช้รหัสสำรองด้านล่างเพื่อเข้าถึงบัญชีของคุณได้ อย่าลืมเก็บรหัสเหล่านี้ไว้ในที่ปลอดภัย แต่ละรหัสสามารถใช้ได้เพียงครั้งเดียวเท่านั้น" backupCodeUsedWarning: "มีการใช้รหัสสำรองแล้ว โปรดกรุณากำหนดค่าการตรวจสอบสิทธิ์แบบสองปัจจัยโดยเร็วที่สุดถ้าหากคุณยังไม่สามารถใช้งานได้อีก" backupCodesExhaustedWarning: "รหัสสำรองทั้งหมดถูกใช้แล้ว ถ้าหากคุณยังสูญเสียการเข้าถึงแอปการตรวจสอบสิทธิ์แบบสองปัจจัยคุณจะยังไม่สามารถเข้าถึงบัญชีนี้ได้ กรุณากำหนดค่าการรับรองความถูกต้องด้วยการยืนยันสองชั้น" + moreDetailedGuideHere: "คลิกที่นี่เพื่อดูคำแนะนำโดยละเอียด" _permissions: "read:account": "ดูข้อมูลบัญชีของคุณ" "write:account": "แก้ไขข้อมูลบัญชีของคุณ" @@ -2014,7 +2036,6 @@ _permissions: "read:admin:server-info": "ดูข้อมูลเซิร์ฟเวอร์" "read:admin:show-moderation-log": "ดูปูมการแก้ไข" "read:admin:show-user": "ดูข้อมูลส่วนตัวของผู้ใช้" - "read:admin:show-users": "ดูข้อมูลส่วนตัวของผู้ใช้" "write:admin:suspend-user": "ระงับผู้ใช้" "write:admin:unset-user-avatar": "ลบอวตารผู้ใช้" "write:admin:unset-user-banner": "ลบแบนเนอร์ผู้ใช้" @@ -2225,6 +2246,7 @@ _play: title: "หัวข้อ" script: "สคริปต์" summary: "รายละเอียด" + visibilityDescription: "หากตั้งค่าเป็นส่วนตัว มันจะไม่ปรากฏในโปรไฟล์อีกต่อไป แต่ผู้ที่ทราบ URL ของมันจะยังสามารถเข้าถึงได้" _pages: newPage: "สร้างหน้าเพจใหม่" editPage: "แก้ไขหน้าเพจ" @@ -2269,6 +2291,8 @@ _pages: section: "ประเภท" image: "รูปภาพ" button: "ปุ่ม" + dynamic: "บล็อกแบบไดนามิก" + dynamicDescription: "บล็อกนี้ล้าสมัยแล้ว โปรดใช้ {play} แทน นับจากนี้เป็นต้นไป" note: "โน้ตที่ฝังตัว" _note: id: "โน้ต ID" @@ -2298,6 +2322,7 @@ _notification: sendTestNotification: "ส่งทดสอบการแจ้งเตือน" notificationWillBeDisplayedLikeThis: "การแจ้งเตือนมีลักษณะแบบนี้" reactedBySomeUsers: "ถูกรีแอคชั่นโดยผู้ใช้ {n} ราย" + likedBySomeUsers: "{n} คนถูกใจ" renotedBySomeUsers: "รีโน้ตจากผู้ใช้ {n} ราย" followedBySomeUsers: "มีผู้ติดตาม {n} ราย" flushNotification: "ล้างประวัติการแจ้งเตือน" @@ -2524,3 +2549,21 @@ _reversi: _offlineScreen: title: "ออฟไลน์ - ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์ได้" header: "ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์ได้" +_urlPreviewSetting: + title: "การตั้งค่าการแสดงตัวอย่าง URL" + enable: "เปิดใช้งานการแสดงตัวอย่าง URL" + timeout: "เวลาจำกัดในการโหลดตัวอย่าง URL (ms)" + timeoutDescription: "หากเวลาที่ใช้ในการโหลดเกินค่านี้ จะไม่มีการสร้างการแสดงตัวอย่าง" + maximumContentLength: "ค่าสูงสุดของ Content-Length (byte)" + maximumContentLengthDescription: "หาก Content-Length เกินค่านี้ จะไม่มีการสร้างการแสดงตัวอย่าง" + requireContentLength: "สร้างการแสดงตัวอย่างเฉพาะในกรณีที่รับ Content-Length ไหว" + requireContentLengthDescription: "หากเซิร์ฟเวอร์อื่นไม่ส่งคืน Content-Length จะไม่มีการสร้างการแสดงตัวอย่าง" + userAgent: "User-Agent" + userAgentDescription: "ตั้งค่า User-Agent ที่ใช้ในการรับการแสดงตัวอย่าง หากเว้นว่างไว้ ระบบจะใช้ User-Agent เริ่มต้น" + summaryProxy: "endpoint ของพร็อกซีที่สร้างการแสดงตัวอย่าง" + summaryProxyDescription: "สร้างการแสดงตัวอย่างด้วย summary Proxy แทนที่จะใช้เนื้อหา Misskey" + summaryProxyDescription2: "พารามิเตอร์ต่อไปนี้จะถูกใช้เป็นสตริงการสืบค้นเพื่อเชื่อมต่อกับพร็อกซี หากฝั่งพร็อกซีไม่รองรับการตั้งค่าเหล่านี้จะถูกละเว้น" +_mediaControls: + pip: "รูปภาพในรูปภาม" + playbackRate: "ความเร็วในการเล่น" + loop: "เล่นวนซ้ำ" diff --git a/locales/tr-TR.yml b/locales/tr-TR.yml index e93a6e43e1..cf6729a81d 100644 --- a/locales/tr-TR.yml +++ b/locales/tr-TR.yml @@ -378,6 +378,10 @@ addMemo: "Kısa not ekle" icon: "Avatar" replies: "yanıt" renotes: "vazgeçme" +_delivery: + stop: "Askıya alınmış" + _type: + none: "Paylaşım" _accountDelete: started: "Silme işlemi başlatıldı" _email: @@ -455,4 +459,3 @@ _deck: _moderationLogTypes: suspend: "askıya al" resetPassword: "Şifre sıfırlama" - diff --git a/locales/ug-CN.yml b/locales/ug-CN.yml index e06cee11a2..e48f64511c 100644 --- a/locales/ug-CN.yml +++ b/locales/ug-CN.yml @@ -17,4 +17,3 @@ _2fa: renewTOTPCancel: "ئۇنى توختىتىڭ" _widgets: profile: "profile" - diff --git a/locales/uk-UA.yml b/locales/uk-UA.yml index df36f43c06..661ecf19d7 100644 --- a/locales/uk-UA.yml +++ b/locales/uk-UA.yml @@ -914,6 +914,10 @@ renotes: "Поширити" sourceCode: "Вихідний код" flip: "Перевернути" lastNDays: "Останні {n} днів" +_delivery: + stop: "Призупинено" + _type: + none: "Публікація" _achievements: earnedAt: "Відкрито" _types: @@ -1623,4 +1627,3 @@ _moderationLogTypes: resetPassword: "Скинути пароль" _reversi: total: "Всього" - diff --git a/locales/uz-UZ.yml b/locales/uz-UZ.yml index a79a76066a..306705e42e 100644 --- a/locales/uz-UZ.yml +++ b/locales/uz-UZ.yml @@ -846,6 +846,10 @@ icon: "Avatar" replies: "Javoblar" renotes: "Qayta qayd etish" flip: "Teskari" +_delivery: + stop: "To'xtatilgan" + _type: + none: "Yuborilmoqda" _achievements: _types: _viewInstanceChart: @@ -1090,4 +1094,3 @@ _moderationLogTypes: resetPassword: "Parolni tiklash" _reversi: total: "Jami" - diff --git a/locales/verify.js b/locales/verify.js new file mode 100644 index 0000000000..63b47c6525 --- /dev/null +++ b/locales/verify.js @@ -0,0 +1,59 @@ +import locales from './index.js'; + +const showUntranslated = process.argv[2] == '-v'; + +let valid = true; + +function writeError(type, lang, tree, data) { + process.stderr.write(JSON.stringify({ type, lang, tree, data })); + process.stderr.write('\n'); + valid = false; +} + +function verify(expected, actual, lang, trace) { + for (let key in expected) { + if (!Object.prototype.hasOwnProperty.call(actual, key)) { + continue; + } + if (typeof expected[key] === 'object') { + if (typeof actual[key] !== 'object') { + writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'object', actual: typeof actual[key] }); + continue; + } + verify(expected[key], actual[key], lang, trace ? `${trace}.${key}` : key); + } else if (typeof expected[key] === 'string') { + switch (typeof actual[key]) { + case 'object': + writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'string', actual: 'object' }); + break; + case 'undefined': + continue; + case 'string': + const expectedParameters = new Set(expected[key].match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1))); + const actualParameters = new Set(actual[key].match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1))); + for (let parameter of expectedParameters) { + if (!actualParameters.has(parameter)) { + writeError('missing_parameter', lang, trace ? `${trace}.${key}` : key, { parameter }); + } + } + + if (showUntranslated && actual[key] == expected[key]) { + writeError('untranslated', lang, trace ? `${trace}.${key}` : key, { original: expected[key] }); + } + } + } + } +} + +const { ['ja-JP']: original, ...verifiees } = locales; + +for (let lang in verifiees) { + if (!Object.prototype.hasOwnProperty.call(locales, lang)) { + continue; + } + verify(original, verifiees[lang], lang); +} + +if (!valid) { + process.exit(1); +} diff --git a/locales/vi-VN.yml b/locales/vi-VN.yml index 15530a5cd3..cf6eafd69f 100644 --- a/locales/vi-VN.yml +++ b/locales/vi-VN.yml @@ -121,9 +121,11 @@ sensitive: "Nhạy cảm" add: "Thêm" reaction: "Biểu cảm" reactions: "Biểu cảm" +emojiPicker: "Bộ chọn biểu tượng cảm xúc" reactionSettingDescription2: "Kéo để sắp xếp, nhấn để xóa, nhấn \"+\" để thêm." rememberNoteVisibility: "Lưu kiểu tút mặc định" attachCancel: "Gỡ tập tin đính kèm" +deleteFile: "Xoá tệp tin" markAsSensitive: "Đánh dấu là nhạy cảm" unmarkAsSensitive: "Bỏ đánh dấu nhạy cảm" enterFileName: "Nhập tên tập tin" @@ -257,6 +259,7 @@ removed: "Đã xóa" removeAreYouSure: "Bạn có chắc muốn gỡ \"{x}\"?" deleteAreYouSure: "Bạn có chắc muốn xóa \"{x}\"?" resetAreYouSure: "Bạn có chắc muốn đặt lại?" +areYouSure: "Bạn chắc chứ?" saved: "Đã lưu" messaging: "Trò chuyện" upload: "Tải lên" @@ -307,6 +310,7 @@ folderName: "Tên thư mục" createFolder: "Tạo thư mục" renameFolder: "Đổi tên thư mục" deleteFolder: "Xóa thư mục" +folder: "Thư mục" addFile: "Thêm tập tin" emptyDrive: "Ổ đĩa của bạn trống trơn" emptyFolder: "Thư mục trống" @@ -368,6 +372,8 @@ hcaptcha: "hCaptcha" enableHcaptcha: "Bật hCaptcha" hcaptchaSiteKey: "Khóa của trang" hcaptchaSecretKey: "Khóa bí mật" +mcaptcha: "mCaptcha" +enableMcaptcha: "Bật mCaptcha" mcaptchaSiteKey: "Khóa của trang" mcaptchaSecretKey: "Khóa bí mật" recaptcha: "reCAPTCHA" @@ -385,6 +391,7 @@ name: "Tên" antennaSource: "Nguồn trạm phát sóng" antennaKeywords: "Từ khóa để nghe" antennaExcludeKeywords: "Từ khóa để lọc ra" +antennaExcludeBots: "Loại trừ các tài khoản bot" antennaKeywordsDescription: "Phân cách bằng dấu cách cho điều kiện AND hoặc bằng xuống dòng cho điều kiện OR." notifyAntenna: "Thông báo có tút mới" withFileAntenna: "Chỉ những tút có media" @@ -537,6 +544,7 @@ showInPage: "Hiện trong trang" popout: "Pop-out" volume: "Âm lượng" masterVolume: "Âm thanh chung" +notUseSound: "Tắt tiếng" details: "Chi tiết" chooseEmoji: "Chọn emoji" unableToProcess: "Không thể hoàn tất hành động" @@ -557,6 +565,10 @@ output: "Nguồn ra" script: "Kịch bản" disablePagesScript: "Tắt AiScript trên Trang" updateRemoteUser: "Cập nhật thông tin người dùng ở máy chủ khác" +unsetUserAvatar: "Gỡ ảnh đại diện" +unsetUserAvatarConfirm: "Bạn có chắc muốn gỡ ảnh đại diện?" +unsetUserBanner: "Gỡ ảnh bìa" +unsetUserBannerConfirm: "Bạn có chắc muốn gỡ ảnh bìa?" deleteAllFiles: "Xóa toàn bộ tập tin" deleteAllFilesConfirm: "Bạn có chắc xóa toàn bộ tập tin?" removeAllFollowing: "Ngưng theo dõi tất cả mọi người" @@ -859,6 +871,8 @@ makeReactionsPublicDescription: "Điều này sẽ hiển thị công khai danh classic: "Cổ điển" muteThread: "Không quan tâm nữa" unmuteThread: "Quan tâm tút này" +followingVisibility: "Hiển thị lượt theo dõi" +followersVisibility: "Hiển thị người theo dõi" continueThread: "Tiếp tục xem chuỗi tút" deleteAccountConfirm: "Điều này sẽ khiến tài khoản bị xóa vĩnh viễn. Vẫn tiếp tục?" incorrectPassword: "Sai mật khẩu." @@ -968,6 +982,7 @@ assign: "Phân công" unassign: "Hủy phân công" color: "Màu sắc" manageCustomEmojis: "Quản lý CustomEmoji" +manageAvatarDecorations: "Quản lý trang trí ảnh đại diện" youCannotCreateAnymore: "Bạn đã tới giới hạn tạo." cannotPerformTemporary: "Tạm thời không sử dụng được" cannotPerformTemporaryDescription: "Tạm thời không sử dụng được vì lần số điều kiện quá giới hạn. Thử lại sau mọt lát nữa." @@ -991,18 +1006,24 @@ copyErrorInfo: "Sao chép thông tin lỗi" joinThisServer: "Đăng ký trên chủ máy này" exploreOtherServers: "Tìm chủ máy khác" letsLookAtTimeline: "Thử xem Timeline" +disableFederationOk: "Vô hiệu hoá" emailNotSupported: "Máy chủ này không hỗ trợ gửi email" postToTheChannel: "Đăng lên kênh" cannotBeChangedLater: "Không thể thay đổi sau này." +likeOnly: "Chỉ lượt thích" rolesAssignedToMe: "Vai trò được giao cho tôi" resetPasswordConfirm: "Bạn thực sự muốn đặt lại mật khẩu?" sensitiveWords: "Các từ nhạy cảm" +prohibitedWords: "Các từ bị cấm" license: "Giấy phép" unfavoriteConfirm: "Bạn thực sự muốn xoá khỏi mục yêu thích?" +retryAllQueuesConfirmTitle: "Bạn có muốn thử lại?" retryAllQueuesConfirmText: "Điều này sẽ tạm thời làm tăng mức độ tải của máy chủ." enableChartsForRemoteUser: "Tạo biểu đồ người dùng từ xa" video: "Video" videos: "Các video" +audio: "Âm thanh" +audioFiles: "Âm thanh" dataSaver: "Tiết kiệm dung lượng" accountMigration: "Chuyển tài khoản" accountMoved: "Người dùng này đã chuyển sang một tài khoản mới:" @@ -1019,36 +1040,88 @@ vertical: "Dọc" horizontal: "Thanh bên" position: "Vị trí" serverRules: "Luật của máy chủ" +pleaseConfirmBelowBeforeSignup: "Để đăng ký trên máy chủ này, bạn phải xem xét và đồng ý với những điều sau." +pleaseAgreeAllToContinue: "Bạn phải đồng ý tất cả điều trên để tiếp tục." +continue: "Tiếp tục" +archive: "Lưu trữ" +thisChannelArchived: "Kênh này đã được lưu trữ." +initialAccountSetting: "Thiết lập hồ sơ" youFollowing: "Đang theo dõi" +preventAiLearning: "Từ chối sử dụng công nghệ Máy Học (AI Sáng Tạo)" +options: "Tùy chọn" +specifyUser: "Người dùng chỉ định" +failedToPreviewUrl: "Không thể xem trước" +update: "Cập nhật" later: "Để sau" goToMisskey: "Tới Misskey" installed: "Đã tải xuống" branding: "Thương hiệu" turnOffToImprovePerformance: "Tắt mục này có thể cải thiện hiệu năng." +createInviteCode: "Tạo lời mời" +createWithOptions: "Tạo cùng tùy chọn" +createCount: "Số lượng mời" +inviteCodeCreated: "Lời mời đã được tạo" +inviteLimitExceeded: "Bạn đã vượt quá số lượng mời mà bạn có thể tạo." +createLimitRemaining: "Giới hạn lượt mời: Còn lại {limit}" +inviteLimitResetCycle: "Giới hạn này sẽ được đặt lại về {limit} lúc {time}." expirationDate: "Ngày hết hạn" noExpirationDate: "Vô thời hạn" +inviteCodeUsedAt: "Mã mời đã được sử dụng lúc" +registeredUserUsingInviteCode: "Lời mời đã được sử dụng bởi" waitingForMailAuth: "Đang chờ xác nhận email" +inviteCodeCreator: "Lời mời đã được tạo bởi" +usedAt: "Sử dụng vào lúc" unused: "Chưa được sử dụng" used: "Đã được sử dụng" expired: "Đã hết hạn" doYouAgree: "Đồng ý?" -iHaveReadXCarefullyAndAgree: "Tôi đã đọc và đồng ý với \"x\"." +beSureToReadThisAsItIsImportant: "Hãy đọc kỹ vì nó rất quan trọng." +iHaveReadXCarefullyAndAgree: "Tôi đã đọc và đồng ý với \"{x}\"." dialog: "Hộp thoại" icon: "Ảnh đại diện" forYou: "Dành cho bạn" currentAnnouncements: "Thông báo hiện tại" pastAnnouncements: "Thông báo trước đó" youHaveUnreadAnnouncements: "Có thông báo chưa đọc." +useSecurityKey: "Làm theo hướng dẫn trên trình duyệt hoặc thiết bị của bạn để sử dụng khóa bảo mật hoặc mật mã." replies: "Trả lời" renotes: "Đăng lại" loadReplies: "Hiển thị các trả lời" +loadConversation: "Xem cuộc trò chuyện" pinnedList: "Các mục đã được ghim" keepScreenOn: "Giữ màn hình luôn bật" verifiedLink: "Chúng tôi đã xác nhận bạn là chủ sở hữu của đường dẫn này" +authentication: "Xác thực" +authenticationRequiredToContinue: "Vui lòng xác thực để tiếp tục" +dateAndTime: "Ngày và giờ" +edited: "Đã chỉnh sửa" +notificationRecieveConfig: "Cài đặt thông báo" +mutualFollow: "Theo dõi lẫn nhau" +followingOrFollower: "Đang theo dõi hoặc người theo dõi" +externalServices: "Các dịch vụ bên ngoài" sourceCode: "Mã nguồn" +feedback: "Phản hồi" +feedbackUrl: "URL phản hồi" +privacyPolicy: "Chính sách bảo mật" +privacyPolicyUrl: "URL Chính sách bảo mật" +tosAndPrivacyPolicy: "Điều khoản sử dụng và Chính sách bảo mật" +avatarDecorations: "Trang trí ảnh đại diện" +attach: "Mặc" +detach: "Bỏ" +detachAll: "Bỏ tất cả" +angle: "Góc" flip: "Lật" +showAvatarDecorations: "Hiển thị trang trí ảnh đại diện" +releaseToRefresh: "Thả để làm mới" +refreshing: "Đang làm mới" +pullDownToRefresh: "Kéo xuống để làm mới" +cwNotationRequired: "Nếu \"Ẩn nội dung\" được bật thì cần phải có chú thích." lastNDays: "{n} ngày trước" surrender: "Từ chối" +_delivery: + stop: "Đã vô hiệu hóa" + _type: + none: "Đang đăng" _announcement: forExistingUsers: "Chỉ những người dùng đã tồn tại" forExistingUsersDescription: "Nếu được bật, thông báo này sẽ chỉ hiển thị với những người dùng đã tồn tại vào lúc thông báo được tạo. Nếu tắt đi, những tài khoản mới đăng ký sau khi thông báo được đăng lên cũng sẽ thấy nó." @@ -1280,6 +1353,7 @@ _role: ltlAvailable: "Xem Timeline trong máy chủ này" canPublicNote: "Cho phép đăng bài công khai" canManageCustomEmojis: "Quản lý CustomEmoji" + canManageAvatarDecorations: "Quản lý trang trí ảnh đại diện" driveCapacity: "Dữ liệu Drive" pinMax: "Giới hạn ghim bài viết" antennaMax: "Giới hạn tạo ăng ten" @@ -1508,7 +1582,6 @@ _2fa: registerTOTP: "Đăng ký ứng dụng xác thực" step1: "Trước tiên, hãy cài đặt một ứng dụng xác minh (chẳng hạn như {a} hoặc {b}) trên thiết bị của bạn." step2: "Sau đó, quét mã QR hiển thị trên màn hình này." - step2Click: "Quét mã QR trên ứng dụng xác thực (Authy, Google authenticator, v.v.)" step3Title: "Nhập mã xác thực" step3: "Nhập mã token do ứng dụng của bạn cung cấp để hoàn tất thiết lập." step4: "Kể từ bây giờ, những lần đăng nhập trong tương lai sẽ yêu cầu mã token đăng nhập đó." @@ -1790,7 +1863,7 @@ _notification: youReceivedFollowRequest: "Bạn vừa có một yêu cầu theo dõi" yourFollowRequestAccepted: "Yêu cầu theo dõi của bạn đã được chấp nhận" pollEnded: "Cuộc bình chọn đã kết thúc" - unreadAntennaNote: "Ăng ten" + unreadAntennaNote: "Ăng ten {name}" emptyPushNotificationMessage: "Đã cập nhật thông báo đẩy" achievementEarned: "Hoàn thành Achievement" _types: @@ -1852,6 +1925,6 @@ _webhookSettings: _moderationLogTypes: suspend: "Vô hiệu hóa" resetPassword: "Đặt lại mật khẩu" + createInvitation: "Tạo lời mời" _reversi: total: "Tổng cộng" - diff --git a/locales/zh-CN.yml b/locales/zh-CN.yml index ddd8914146..7d1148909f 100644 --- a/locales/zh-CN.yml +++ b/locales/zh-CN.yml @@ -58,7 +58,7 @@ copyUserId: "复制用户 ID" copyNoteId: "复制帖子 ID" copyFileId: "复制文件ID" copyFolderId: "复制文件夹ID" -copyProfileUrl: "复制配置文件URL" +copyProfileUrl: "复制个人资料URL" searchUser: "搜索用户" reply: "回复" loadMore: "查看更多" @@ -108,11 +108,14 @@ enterEmoji: "输入表情符号" renote: "转发" unrenote: "取消转发" renoted: "已转发。" +renotedToX: "转帖给 {name}" cantRenote: "该帖无法转发。" cantReRenote: "转发无法被再次转发。" quote: "引用" inChannelRenote: "在频道内转发" inChannelQuote: "在频道内引用" +renoteToChannel: "转帖至频道" +renoteToOtherChannel: "转帖至其它频道" pinnedNote: "已置顶的帖子" pinned: "置顶" you: "您" @@ -313,6 +316,7 @@ selectFile: "选择文件" selectFiles: "选择文件" selectFolder: "选择文件夹" selectFolders: "选择多个文件夹" +fileNotSelected: "未选择文件" renameFile: "重命名文件" folderName: "文件夹名称" createFolder: "创建文件夹" @@ -400,6 +404,7 @@ name: "名称" antennaSource: "接收来源" antennaKeywords: "包含关键字" antennaExcludeKeywords: "排除关键字" +antennaExcludeBots: "排除机器人账户" antennaKeywordsDescription: "AND 条件用空格分隔,OR 条件用换行符分隔。" notifyAntenna: "开启通知" withFileAntenna: "仅带有附件的帖子" @@ -467,6 +472,7 @@ retype: "重新输入" noteOf: "{user} 的帖子" quoteAttached: "已引用" quoteQuestion: "是否引用此链接内容?" +attachAsFileQuestion: "剪贴板内的文字过长。要转换为文本文件并添加吗?" noMessagesYet: "现在没有新的聊天" newMessageExists: "新信息" onlyOneFileCanBeAttached: "只能添加一个附件" @@ -494,6 +500,7 @@ emojiStyle: "表情符号的样式" native: "原生" disableDrawer: "不显示抽屉菜单" showNoteActionsOnlyHover: "仅在悬停时显示帖子操作" +showReactionsCount: "显示帖子的回应数" noHistory: "没有历史记录" signinHistory: "登录历史" enableAdvancedMfm: "启用扩展 MFM" @@ -614,7 +621,7 @@ disablePlayer: "关闭播放器" expandTweet: "展开帖子" themeEditor: "主题编辑器" description: "描述" -describeFile: "添加标题" +describeFile: "添加描述" enterFileDescription: "输入标题" author: "作者" leaveConfirm: "存在未保存的更改。要放弃更改吗?" @@ -1019,6 +1026,7 @@ thisPostMayBeAnnoyingHome: "发到首页" thisPostMayBeAnnoyingCancel: "取消" thisPostMayBeAnnoyingIgnore: "就这样发布" collapseRenotes: "省略显示已经看过的转发内容" +collapseRenotesDescription: "将回应过或转贴过的贴子折叠表示。" internalServerError: "内部服务器错误" internalServerErrorDescription: "内部服务器发生了预期外的错误" copyErrorInfo: "复制错误信息" @@ -1201,7 +1209,7 @@ code: "代码" reloadRequiredToApplySettings: "需要重新载入来使设置生效" remainingN: "剩余:{n}" overwriteContentConfirm: "将覆盖现有内容。确定吗?" -seasonalScreenEffect: "应景的画面效果" +seasonalScreenEffect: "符合当前季节的画面效果" decorate: "装饰" addMfmFunction: "添加装饰" enableQuickAddMfmFunction: "显示高级 MFM 选择器" @@ -1223,6 +1231,25 @@ enableHorizontalSwipe: "滑动切换标签页" loading: "读取中" surrender: "取消" gameRetry: "重试" +notUsePleaseLeaveBlank: "如不使用请留空" +useTotp: "使用一次性代码" +useBackupCode: "使用备用代码" +launchApp: "启动应用" +useNativeUIForVideoAudioPlayer: "使用浏览器的 UI 播放动画及音频" +keepOriginalFilename: "保持原文件名" +keepOriginalFilenameDescription: "若关闭此设置,上传文件时文件名将被替换为随机字符。" +noDescription: "没有描述" +alwaysConfirmFollow: "总是确认关注" +inquiry: "联系我们" +_delivery: + status: "投递状态" + stop: "停止投递" + resume: "继续投递" + _type: + none: "投递中" + manuallySuspended: "手动停止中" + goneSuspended: "因服务器被删除而停止" + autoSuspendedForNotResponding: "因服务器无应答而停止" _bubbleGame: howToPlay: "游戏说明" hold: "抓住" @@ -1233,6 +1260,7 @@ _bubbleGame: maxChain: "最高连击数" yen: "{yen} 日元" estimatedQty: "约 {qty} 个" + scoreSweets: "相当于 {onigiriQtyWithUnit} 饭团" _howToPlay: section1: "对准位置将Emoji投入盒子。" section2: "相同的Emoji相互接触合成后会得到新的Emoji,以此获得分数。" @@ -1350,7 +1378,7 @@ _serverSettings: _accountMigration: moveFrom: "从别的账号迁移到此账户" moveFromSub: "为另一个账户建立别名" - moveFromLabel: "迁移前的账户" + moveFromLabel: "迁移前的账户 #{n}" moveFromDescription: "如果迁移时需要继承其他账户的关注者,你需要创建一个别名。此操作需要在迁移前完成!\n请像这样输入要迁移的账户:@username@server.example.com\n如果要删除,请将输入字段留空,并保存(不推荐)。" moveTo: "把这个账户迁移到新的账户" moveToLabel: "迁移后的账户" @@ -1680,6 +1708,11 @@ _role: roleAssignedTo: "已分配给手动角色" isLocal: "是本地用户" isRemote: "是远程用户" + isCat: "猫猫用户" + isBot: "机器人用户" + isSuspended: "停用的用户" + isLocked: "锁推用户" + isExplorable: "启用“使账号可见”的用户" createdLessThan: "账户创建时间少于" createdMoreThan: "账户创建时间超过" followersLessThanOrEq: "关注者不多于" @@ -1749,6 +1782,7 @@ _plugin: installWarn: "请不要安装不可信的插件。" manage: "管理插件..." viewSource: "查看源代码" + viewLog: "显示日志" _preferencesBackups: list: "已创建的备份" saveNew: "另存为" @@ -1938,7 +1972,6 @@ _2fa: registerTOTP: "开始设置认证应用" step1: "首先,在您的设备上安装验证应用,例如 {a} 或 {b}。" step2: "然后,扫描屏幕上显示的二维码。" - step2Click: "通过点击二维码,您可以使用设备上安装的身份验证器应用程序或密钥环进行注册" step2Uri: "如果使用桌面应用程序的话,请输入下面的 URI" step3Title: "输入验证码" step3: "输入您的应用提供的动态口令以完成设置。" @@ -1962,6 +1995,7 @@ _2fa: backupCodesDescription: "如果无法使用认证应用,可以使用以下的备用代码来访问账户。请务必将这些代码保存在安全的地方。每个代码仅可使用一次。" backupCodeUsedWarning: "已使用备用代码。如果无法使用认证应用,请尽快重新设定。" backupCodesExhaustedWarning: "已使用完所有的备用代码。如果无法使用认证应用,将无法再访问您的账户。请再次设定认证应用。" + moreDetailedGuideHere: "此处为详细指南" _permissions: "read:account": "查看账户信息" "write:account": "更改帐户信息" @@ -2012,7 +2046,6 @@ _permissions: "read:admin:server-info": "查看服务器信息" "read:admin:show-moderation-log": "查看管理日志" "read:admin:show-user": "查看用户的非公开信息" - "read:admin:show-users": "查看用户的非公开信息" "write:admin:suspend-user": "冻结用户" "write:admin:unset-user-avatar": "删除用户头像" "write:admin:unset-user-banner": "删除用户横幅" @@ -2223,6 +2256,7 @@ _play: title: "标题" script: "脚本" summary: "描述" + visibilityDescription: "设置为不公开后资料将不再显示,但知道 URL 的人仍可继续访问。" _pages: newPage: "创建页面" editPage: "编辑页面" @@ -2267,6 +2301,8 @@ _pages: section: "章节" image: "图片" button: "按钮" + dynamic: "动态区块" + dynamicDescription: "这个区块已经废弃。以后请使用{play}。" note: "嵌入的帖子" _note: id: "帖子 ID" @@ -2296,6 +2332,7 @@ _notification: sendTestNotification: "发送测试通知" notificationWillBeDisplayedLikeThis: "通知将会这样表示" reactedBySomeUsers: "{n} 人回应了" + likedBySomeUsers: "{n}人赞了你的帖子" renotedBySomeUsers: "{n} 人转发了" followedBySomeUsers: "被 {n} 人关注" flushNotification: "重置通知历史" @@ -2322,6 +2359,7 @@ _deck: alwaysShowMainColumn: "总是显示主列" columnAlign: "列对齐" addColumn: "添加列" + newNoteNotificationSettings: "新帖子通知设定" configureColumn: "列设置" swapLeft: "向左移动" swapRight: "向右移动" @@ -2478,6 +2516,7 @@ _hemisphere: _reversi: reversi: "黑白棋" gameSettings: "对局设置" + chooseBoard: "选择棋盘" blackOrWhite: "先手/后手" blackIs: "{name}执黑(先手)" rules: "规则" @@ -2504,6 +2543,8 @@ _reversi: allGames: "所有对局" ended: "结束" playing: "对局中" + isLlotheo: "落子少的一方获胜(又名奥赛罗)" + loopedMap: "循环棋盘" canPutEverywhere: "无限制放置模式" timeLimitForEachTurn: "1回合的时间限制" freeMatch: "自由匹配" @@ -2519,3 +2560,21 @@ _reversi: _offlineScreen: title: "离线——无法连接到服务器" header: "无法连接到服务器" +_urlPreviewSetting: + title: "设置 URL 预览" + enable: "启用 URL 预览" + timeout: "超时阈值(ms)" + timeoutDescription: "如果获取预览所用时间超过这个值,则不生成预览。" + maximumContentLength: "Content-Length 的最大值(byte)" + maximumContentLengthDescription: "如果 Content-Length 超过这个值,则不生成预览。" + requireContentLength: "仅在能取得 Content-Length 时生成预览" + requireContentLengthDescription: "如果目标服务器不返回 Content-Length,则不生成预览。" + userAgent: "User-Agent" + userAgentDescription: "设定获取预览时使用的 User-Agent。留空时将使用默认的 User-Agent。" + summaryProxy: "用来生成预览的代理的 endpoint。" + summaryProxyDescription: "不使用 Misskey 本体,而是通过 Summaly Proxy 生成预览。" + summaryProxyDescription2: "下面的参数将作为查询字符串发送至代理。代理侧如果不支持此设置,则忽略设定值。" +_mediaControls: + pip: "画中画" + playbackRate: "播放速度" + loop: "循环播放" diff --git a/locales/zh-TW.yml b/locales/zh-TW.yml index f8bdd002b4..78116254ba 100644 --- a/locales/zh-TW.yml +++ b/locales/zh-TW.yml @@ -108,11 +108,14 @@ enterEmoji: "輸入表情符號" renote: "轉發" unrenote: "取消轉發" renoted: "轉發成功。" +renotedToX: "轉發給 {name} 了。" cantRenote: "無法轉發此貼文。" cantReRenote: "無法轉發之前已經轉發過的內容。" quote: "引用" inChannelRenote: "在頻道內轉發" inChannelQuote: "在頻道內引用" +renoteToChannel: "轉發至頻道" +renoteToOtherChannel: "轉發至其他頻道" pinnedNote: "已置頂的貼文" pinned: "置頂" you: "您" @@ -169,7 +172,7 @@ cacheRemoteSensitiveFilesDescription: "若停用這個設定,則不會快取 flagAsBot: "此使用者是機器人" flagAsBotDescription: "如果本帳戶是由程式控制,請啟用此選項。啟用後,會作為標示幫助其他開發者防止機器人之間產生無限互動的行為,並會調整 Misskey 內部系統將本帳戶識別為機器人。" flagAsCat: "此帳戶是一隻貓,喵~~~!!!" -flagAsCatDescription: "如果想將本帳戶標示為一隻貓,請開啟此標示" +flagAsCatDescription: "喵喵喵??" flagShowTimelineReplies: "在時間軸上顯示貼文的回覆" flagShowTimelineRepliesDescription: "啟用後,時間軸除了顯示使用者的貼文以外,還會顯示使用者對其他貼文的回覆。" autoAcceptFollowed: "自動允許來自追隨中使用者的追隨請求" @@ -205,7 +208,7 @@ silenceThisInstance: "禁言此伺服器" operations: "操作" software: "軟體" version: "版本" -metadata: "元資料" +metadata: "詮釋資料" withNFiles: "{n} 個檔案" monitor: "監視器" jobQueue: "佇列" @@ -313,6 +316,7 @@ selectFile: "選擇檔案" selectFiles: "選擇檔案" selectFolder: "選擇資料夾" selectFolders: "選擇資料夾" +fileNotSelected: "尚未選擇檔案" renameFile: "重新命名檔案" folderName: "資料夾名稱" createFolder: "新增資料夾" @@ -366,7 +370,7 @@ enableRegistration: "開放新使用者註冊" invite: "邀請" driveCapacityPerLocalAccount: "每個本地使用者的雲端硬碟容量" driveCapacityPerRemoteAccount: "每個非本地用戶的雲端空間大小" -inMb: "以Mbps為單位" +inMb: "以 MB 為單位" bannerUrl: "橫幅圖片URL" backgroundImageUrl: "背景圖片的來源網址 " basicInfo: "基本資訊" @@ -378,12 +382,12 @@ pinnedClipId: "置頂的摘錄ID" pinnedNotes: "已置頂的貼文" hcaptcha: "hCaptcha" enableHcaptcha: "啟用 hCaptcha" -hcaptchaSiteKey: "網站金鑰" -hcaptchaSecretKey: "金鑰" +hcaptchaSiteKey: "hcaptchaSiteKey" +hcaptchaSecretKey: "hcaptchaSecretKey" mcaptcha: "mCaptcha" enableMcaptcha: "啟用 mCaptcha" mcaptchaSiteKey: "網站金鑰" -mcaptchaSecretKey: "金鑰" +mcaptchaSecretKey: "私密金鑰" mcaptchaInstanceUrl: "mCaptcha 的實例網址" recaptcha: "reCAPTCHA" enableRecaptcha: "啟用 reCAPTCHA" @@ -391,8 +395,8 @@ recaptchaSiteKey: "網站金鑰" recaptchaSecretKey: "金鑰" turnstile: "Turnstile" enableTurnstile: "啟用 Turnstile" -turnstileSiteKey: "網站金鑰" -turnstileSecretKey: "金鑰" +turnstileSiteKey: "turnstileSiteKey" +turnstileSecretKey: "turnstileSecretKey" avoidMultiCaptchaConfirm: "使用多種驗證方式可能會造成干擾,您要關閉其他驗證方式嗎?您可以按「取消」保留多種驗證方式。" antennas: "天線" manageAntennas: "管理天線" @@ -400,6 +404,7 @@ name: "名稱" antennaSource: "接收來源" antennaKeywords: "包含關鍵字" antennaExcludeKeywords: "排除關鍵字" +antennaExcludeBots: "排除機器人帳戶" antennaKeywordsDescription: "空格代表「以及」(AND),換行代表「或者」(OR)" notifyAntenna: "通知有新貼文" withFileAntenna: "僅帶有附件的貼文" @@ -463,10 +468,11 @@ title: "標題" text: "文字" enable: "啟用" next: "下一步" -retype: "再次輸入" +retype: "重新輸入" noteOf: "{user}的貼文" quoteAttached: "引用" quoteQuestion: "是否要引用?" +attachAsFileQuestion: "剪貼簿的文字較長。請問是否要將其以文字檔的方式附加呢?" noMessagesYet: "沒有訊息" newMessageExists: "有新的訊息" onlyOneFileCanBeAttached: "只能加入一個附件" @@ -494,6 +500,7 @@ emojiStyle: "表情符號的風格" native: "原生" disableDrawer: "不顯示下拉式選單" showNoteActionsOnlyHover: "僅在游標停留時顯示貼文的操作選項" +showReactionsCount: "顯示貼文的反應數目" noHistory: "沒有歷史紀錄" signinHistory: "登入歷史" enableAdvancedMfm: "啟用進階 MFM" @@ -600,7 +607,7 @@ addItem: "新增項目" rearrange: "排序方式" relays: "中繼器" addRelay: "新增中繼器" -inboxUrl: "收件夾URL" +inboxUrl: "收件夾 URL" addedRelays: "已加入的中繼器" serviceworkerInfo: "如要使用推播通知,需要啟用此選項並設定金鑰。" deletedNote: "已刪除的貼文" @@ -750,7 +757,7 @@ experimentalFeatures: "實驗中的功能" experimental: "實驗性" thisIsExperimentalFeature: "這是實驗性的功能。可能會有變更規格和不能正常動作的可能性。" developer: "開發者" -makeExplorable: "使自己的帳戶能夠在「探索」頁面中顯示" +makeExplorable: "使自己的帳戶更容易被找到" makeExplorableDescription: "如果關閉,帳戶將不會被顯示在「探索」頁面中。" showGapBetweenNotesInTimeline: "分開顯示時間軸上的貼文" duplicate: "複製" @@ -789,7 +796,7 @@ newVersionOfClientAvailable: "新版本的客戶端可用。" usageAmount: "使用量" capacity: "容量" inUse: "已使用" -editCode: "編輯代碼" +editCode: "編輯程式碼" apply: "套用" receiveAnnouncementFromInstance: "接收來自伺服器的通知" emailNotification: "郵件通知" @@ -1019,6 +1026,7 @@ thisPostMayBeAnnoyingHome: "發佈到首頁" thisPostMayBeAnnoyingCancel: "退出" thisPostMayBeAnnoyingIgnore: "直接發佈貼文" collapseRenotes: "省略顯示已看過的轉發貼文" +collapseRenotesDescription: "將已做過反應和轉發的貼文折疊顯示。" internalServerError: "內部伺服器錯誤" internalServerErrorDescription: "內部伺服器出現意外錯誤。" copyErrorInfo: "複製錯誤資訊" @@ -1060,7 +1068,7 @@ enableChartsForFederatedInstances: "生成遠端伺服器的圖表" showClipButtonInNoteFooter: "新增摘錄按鈕至貼文" reactionsDisplaySize: "反應的顯示尺寸" limitWidthOfReaction: "限制反應的最大寬度,並縮小顯示尺寸。" -noteIdOrUrl: "貼文ID或URL" +noteIdOrUrl: "貼文 ID 或 URL" video: "影片" videos: "影片" audio: "音效" @@ -1075,7 +1083,7 @@ addMemo: "新增備註" editMemo: "編輯備註" reactionsList: "反應列表" renotesList: "轉發貼文列表" -notificationDisplay: "通知的顯示" +notificationDisplay: "通知" leftTop: "左上" rightTop: "右上" leftBottom: "左下" @@ -1177,15 +1185,15 @@ repositoryUrlOrTarballRequired: "如果儲存庫不是公開的,則必須提 feedback: "意見回饋" feedbackUrl: "意見回饋 URL" impressum: "營運者資訊" -impressumUrl: "營運者資訊網址" +impressumUrl: "營運者資訊 URL" impressumDescription: "在德國與部份地區必須要明確顯示營運者資訊。" privacyPolicy: "隱私政策" -privacyPolicyUrl: "隱私政策網址" +privacyPolicyUrl: "隱私政策 URL" tosAndPrivacyPolicy: "服務條款和隱私政策" avatarDecorations: "頭像裝飾" attach: "裝上" detach: "取下" -detachAll: "移除所有裝飾" +detachAll: "全部移除" angle: "角度" flip: "翻轉" showAvatarDecorations: "顯示頭像裝飾" @@ -1203,7 +1211,7 @@ remainingN: "剩餘:{n}" overwriteContentConfirm: "確定要覆蓋目前的內容嗎?" seasonalScreenEffect: "隨季節變換畫面的呈現" decorate: "設置頭像裝飾" -addMfmFunction: "插入MFM功能語法" +addMfmFunction: "插入 MFM 功能語法" enableQuickAddMfmFunction: "顯示高級 MFM 選擇器" bubbleGame: "氣泡遊戲" sfx: "音效" @@ -1223,6 +1231,25 @@ enableHorizontalSwipe: "滑動切換時間軸" loading: "載入中" surrender: "退出" gameRetry: "再試一次" +notUsePleaseLeaveBlank: "如果不使用的話請留白" +useTotp: "使用一次性密碼" +useBackupCode: "使用備用驗證碼" +launchApp: "啟動 APP" +useNativeUIForVideoAudioPlayer: "使用瀏覽器的 UI 播放影片與音訊" +keepOriginalFilename: "保留原始檔名" +keepOriginalFilenameDescription: "如果關閉此設置,上傳時檔案名稱會自動替換為隨機字串。" +noDescription: "沒有說明文字" +alwaysConfirmFollow: "點擊追隨時總是顯示確認訊息" +inquiry: "聯絡我們" +_delivery: + status: "傳送狀態" + stop: "停止傳送" + resume: "恢復傳送" + _type: + none: "直播中" + manuallySuspended: "手動暫停中" + goneSuspended: "因為伺服器刪除所以暫停中" + autoSuspendedForNotResponding: "因為伺服器沒有回應所以暫停中" _bubbleGame: howToPlay: "玩法說明" hold: "保留" @@ -1231,7 +1258,7 @@ _bubbleGame: scoreYen: "賺取的金額" highScore: "最高分" maxChain: "最大結合數" - yen: "{yen} 日圓" + yen: "{yen}円" estimatedQty: "{qty}個" scoreSweets: "飯糰 {onigiriQtyWithUnit}" _howToPlay: @@ -1259,7 +1286,7 @@ _initialAccountSetting: privacySetting: "隱私設定" theseSettingsCanEditLater: "這裡的設定可以在之後變更。" youCanEditMoreSettingsInSettingsPageLater: "除此之外,還可以在「設定」頁面進行各種設定。之後請確認看看。" - followUsers: "為了構築時間軸,試著追蹤您感興趣的使用者吧。" + followUsers: "為了構築時間軸,試著追隨您感興趣的使用者吧。" pushNotificationDescription: "啟用推送通知,就可以在設備上接收{name}的通知。" initialAccountSettingCompleted: "初始設定完成了!" haveFun: "盡情享受{name}吧!" @@ -1314,7 +1341,7 @@ _initialTutorial: title: "隱藏內容(CW)" description: "將顯示「註釋」中寫入的內容而不是本文。按一下「顯示內容」以顯示本文。" _exampleNote: - cw: "美食恐怖主義注意" + cw: "注意消夜文" note: "我吃了一個巧克力甜甜圈🍩😋" useCases: "伺服器的服務條款可能會規範特定的貼文需要使用隱藏內容,除此之外也會用在隱藏劇情洩漏與敏感內容的貼文。" _howToMakeAttachmentsSensitive: @@ -1339,7 +1366,7 @@ _serverRules: _serverSettings: iconUrl: "圖示的 URL" appIconDescription: "指定顯示 {host} 為應用程式時的圖示。" - appIconUsageExample: "例如:漸進式網路應用程式(PWA)、於手機桌面新增書籤" + appIconUsageExample: "例如:PWA 或是在手機桌面作為書籤等" appIconStyleRecommendation: "因為可能會裁剪成圓形或圓角,所以建議用單色填滿邊框及背景。" appIconResolutionMustBe: "解析度必須為 {resolution}。" manifestJsonOverride: "覆寫 manifest.json" @@ -1348,10 +1375,12 @@ _serverSettings: fanoutTimelineDescription: "如果啟用的話,檢索各個時間軸的性能會顯著提昇,資料庫的負荷也會減少。不過,Redis 的記憶體使用量會增加。如果伺服器的記憶體容量比較少或者運行不穩定,可以停用。" fanoutTimelineDbFallback: "資料庫的回退" fanoutTimelineDbFallbackDescription: "若啟用,在時間軸沒有快取的情況下將執行回退處理以額外查詢資料庫。若停用,可以透過不執行回退處理來進一步減少伺服器的負荷,但會限制可取得的時間軸範圍。" + inquiryUrl: "聯絡表單網址" + inquiryUrlDescription: "指定伺服器運營者的聯絡表單網址或包含運營者聯絡資訊網頁的網址。" _accountMigration: moveFrom: "從其他帳戶遷移到這個帳戶" moveFromSub: "為另一個帳戶建立別名" - moveFromLabel: "要遷移過來的帳戶:" + moveFromLabel: "要遷移過來的帳戶 #{n}" moveFromDescription: "如果你想把追隨者從別的帳戶遷移過來,必須先在這裡建立別名。請務必在執行遷移之前建立別名!請像這樣輸入要遷移的帳戶:@person@instance.com" moveTo: "將這個帳戶遷移至新的帳戶" moveToLabel: "要遷移到的帳戶:" @@ -1547,7 +1576,7 @@ _achievements: _postedAt0min0sec: title: "報時" description: "在零分零秒發佈貼文" - flavor: "啵、啵、啵、嗶ーー" + flavor: "啵.啵.啵.嗶ー" _selfQuote: title: "自我引用" description: "引用了自己的貼文" @@ -1682,6 +1711,11 @@ _role: roleAssignedTo: "手動指派角色完成" isLocal: "本地使用者" isRemote: "遠端使用者" + isCat: "貓使用者" + isBot: "機器人使用者" + isSuspended: "被停權的使用者" + isLocked: "上鎖的使用者" + isExplorable: "開啟了「使您的帳戶更容易被找到」功能的使用者" createdLessThan: "帳戶加入時間不超過" createdMoreThan: "帳戶加入時間已超過" followersLessThanOrEq: "追隨者人數在~以下" @@ -1751,6 +1785,7 @@ _plugin: installWarn: "請不要安裝來源不明的外掛。" manage: "管理外掛" viewSource: "檢視原始碼" + viewLog: "顯示記錄 " _preferencesBackups: list: "已備份的設定檔" saveNew: "另存新檔" @@ -1839,7 +1874,7 @@ _theme: invalid: "佈景主題格式錯誤" make: "製作佈景主題" base: "基於" - addConstant: "添加常數" + addConstant: "新增常數" constant: "常數" defaultValue: "預設值" color: "顏色" @@ -1914,22 +1949,22 @@ _soundSettings: _ago: future: "未來" justNow: "剛剛" - secondsAgo: "{n} 秒前" - minutesAgo: "{n} 分鐘前 " - hoursAgo: "{n} 小時前" - daysAgo: "{n} 天前" - weeksAgo: "{n} 週前" - monthsAgo: "{n} 個月前" - yearsAgo: "{n} 年前" + secondsAgo: "{n}秒前" + minutesAgo: "{n}分鐘前" + hoursAgo: "{n}小時前" + daysAgo: "{n}天前" + weeksAgo: "{n}周前" + monthsAgo: "{n}個月前" + yearsAgo: "{n}年前" invalid: "無" _timeIn: - seconds: "{n} 秒後" - minutes: "{n} 分後" - hours: "{n} 小時後" - days: "{n} 日後" - weeks: "{n} 週後" - months: "{n} 個月後" - years: "{n} 年後" + seconds: "{n}秒後" + minutes: "{n}分鐘後" + hours: "{n}小時後" + days: "{n}天後" + weeks: "{n}周後" + months: "{n}個月後" + years: "{n}年後" _time: second: "秒" minute: "分鐘" @@ -1940,7 +1975,6 @@ _2fa: registerTOTP: "開始設定驗證應用程式" step1: "首先,在您的裝置上安裝驗證程式,例如 {a} 或 {b}。" step2: "然後,掃描螢幕上的 QR 碼。" - step2Click: "您可以點擊 QR 碼,以使用裝置上的驗證應用程式或金鑰環註冊。" step2Uri: "使用桌面版應用程式時,請輸入以下的 URI" step3Title: "輸入驗證碼" step3: "輸入應用程式所提供的權杖以完成設定。" @@ -1964,6 +1998,7 @@ _2fa: backupCodesDescription: "如果驗證應用程式不能用了,可以使用以下的備用驗證碼存取您的帳戶。請務必妥善保管這個驗證碼。每個驗證碼只能使用一次。" backupCodeUsedWarning: "已使用備用驗證碼。如果無法使用驗證應用程式,請盡快重新設定。" backupCodesExhaustedWarning: "已使用所有備用驗證碼。如果無法使用驗證應用程式,則將無法再存取您的帳戶。請重新設定您的驗證應用程式。" + moreDetailedGuideHere: "請點擊此處查看詳細說明。" _permissions: "read:account": "查看我的帳戶資訊" "write:account": "更改我的帳戶資訊" @@ -2007,19 +2042,18 @@ _permissions: "read:admin:index-stats": "查看資料庫索引的相關資訊" "read:admin:table-stats": "查看資料庫表格的相關資訊" "read:admin:user-ips": "查看使用者的 IP 位址" - "read:admin:meta": "查看實例的元資料" + "read:admin:meta": "查看實例的詮釋資料" "write:admin:reset-password": "重設使用者的密碼" "write:admin:resolve-abuse-user-report": "解決來自使用者的檢舉" "write:admin:send-email": "發送郵件" "read:admin:server-info": "查看伺服器的資訊" "read:admin:show-moderation-log": "查看審查紀錄" "read:admin:show-user": "查看使用者的私密資訊" - "read:admin:show-users": "查看使用者的私密資訊" "write:admin:suspend-user": "凍結使用者" "write:admin:unset-user-avatar": "刪除使用者的頭像" "write:admin:unset-user-banner": "刪除使用者的橫幅" "write:admin:unsuspend-user": "解除凍結使用者" - "write:admin:meta": "編輯實例的元資料" + "write:admin:meta": "編輯實例的詮釋資料" "write:admin:user-note": "編輯審查筆記" "write:admin:roles": "編輯角色" "read:admin:roles": "查看角色" @@ -2067,13 +2101,13 @@ _antennaSources: userList: "來自特定清單中的貼文" userBlacklist: "除指定使用者外的所有貼文" _weekday: - sunday: "週日" - monday: "週一" - tuesday: "週二" - wednesday: "週三" - thursday: "週四" - friday: "週五" - saturday: "週六" + sunday: "星期天" + monday: "星期一" + tuesday: "星期二" + wednesday: "星期三" + thursday: "星期四" + friday: "星期五" + saturday: "星期六" _widgets: profile: "個人檔案" instanceInfo: "伺服器資訊" @@ -2122,7 +2156,7 @@ _poll: deadlineDate: "截止日期" deadlineTime: "小時" duration: "時長" - votesCount: "{n} 票" + votesCount: "{n}票" totalVotes: "合計 {n} 票" vote: "投票" showResult: "顯示結果" @@ -2155,7 +2189,7 @@ _postForm: e: "寫些什麼吧……" f: "靜待發文……" _profile: - name: "名稱" + name: "名字" username: "使用者名稱" description: "關於我" youCanIncludeHashtags: "你也可以在「關於我」中加上 #tag" @@ -2188,7 +2222,7 @@ _charts: notesIncDec: "貼文増減" localNotesIncDec: "本地貼文増減" remoteNotesIncDec: "遠端貼文數目增减" - notesTotal: "貼文合共" + notesTotal: "貼文總數" filesIncDec: "檔案增減" filesTotal: "檔案總數" storageUsageIncDec: "儲存空間增減" @@ -2213,10 +2247,10 @@ _timelines: _play: new: "新增 Play" edit: "編輯 Play" - created: "已新增Play " - updated: "已更新Play " + created: "已新增 Play " + updated: "已更新 Play " deleted: "已刪除 Play" - pageSetting: "Play設定" + pageSetting: "Play 設定" editThisPage: "編輯此 Play" viewSource: "檢視原始碼" my: "自己的 Play" @@ -2225,10 +2259,11 @@ _play: title: "標題" script: "腳本" summary: "描述" + visibilityDescription: "如果您將其設為私密,它將不再顯示在您的個人資料中,但知道該 URL 的人仍然可以存取它。" _pages: newPage: "建立頁面" editPage: "編輯頁面" - readPage: "正檢視原始碼" + readPage: "正在檢視原始碼" created: "頁面已建立" updated: "頁面已更新" deleted: "頁面已被刪除" @@ -2255,7 +2290,7 @@ _pages: hideTitleWhenPinned: "被置頂於個人資料時隱藏頁面標題" font: "字型" fontSerif: "襯線體" - fontSansSerif: "無襯線體" + fontSansSerif: "黑體" eyeCatchingImageSet: "設定封面影像" eyeCatchingImageRemove: "刪除封面影像" chooseBlock: "新增方塊" @@ -2269,6 +2304,8 @@ _pages: section: "區段" image: "圖片" button: "按鈕" + dynamic: "動態方塊" + dynamicDescription: "這個方塊已經廢止,現在開始請使用 {play}。" note: "嵌式貼文" _note: id: "貼文ID" @@ -2298,6 +2335,7 @@ _notification: sendTestNotification: "發送測試通知" notificationWillBeDisplayedLikeThis: "通知會以這樣的方式顯示" reactedBySomeUsers: "{n}人做出了反應" + likedBySomeUsers: "{n} 人按了讚" renotedBySomeUsers: "{n}人做了轉發" followedBySomeUsers: "被{n}人追隨了" flushNotification: "重置通知歷史紀錄" @@ -2324,6 +2362,7 @@ _deck: alwaysShowMainColumn: "總是顯示主欄" columnAlign: "對齊欄位" addColumn: "新增欄位" + newNoteNotificationSettings: "新貼文通知的設定" configureColumn: "欄位的設定" swapLeft: "向左移動" swapRight: "向右移動" @@ -2362,7 +2401,7 @@ _drivecleaner: orderByCreatedAtAsc: "按新增日期降序排列" _webhookSettings: createWebhook: "建立 Webhook" - name: "名稱" + name: "名字" secret: "密鑰" events: "何時運行 Webhook" active: "已啟用" @@ -2524,3 +2563,21 @@ _reversi: _offlineScreen: title: "離線-無法連接伺服器" header: "無法連接伺服器" +_urlPreviewSetting: + title: "URL 預覽設定" + enable: "啟用 URL 預覽" + timeout: "取得預覽的逾時時間 (ms)" + timeoutDescription: "若取得預覽所需的時間超過這個值,則不會產生預覽。" + maximumContentLength: "Content-Length 的最大値 (byte)" + maximumContentLengthDescription: "若 Content-Length 超過這個值,則不會產生預覽。" + requireContentLength: "僅在能夠取得 Content-Length 時,才產生預覽。" + requireContentLengthDescription: "若對方的伺服器未回傳 Content -Length,則不會產生預覽。" + userAgent: "User-Agent" + userAgentDescription: "設定獲取預覽時使用的 User-Agent 。如果留空,將使用預設的 User-Agent 。" + summaryProxy: "產生預覽的代理端點" + summaryProxyDescription: "使用摘要代理程式而不是 Misskey 本身產生預覽。" + summaryProxyDescription2: "以下參數會作為查詢字串連結到代理。如果代理端不支援,這些設定將被忽略。" +_mediaControls: + pip: "畫中畫" + playbackRate: "播放速度" + loop: "循環播放" diff --git a/package.json b/package.json index 1d6d521ccd..2ff23d3a74 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "sharkey", - "version": "2024.3.3-devel", + "version": "2024.5.0", "codename": "shonk", "repository": { "type": "git", "url": "https://activitypub.software/TransFem-org/Sharkey.git" }, - "packageManager": "pnpm@8.15.4", + "packageManager": "pnpm@9.0.6", "workspaces": [ "packages/frontend", "packages/backend", @@ -48,21 +48,24 @@ "lodash": "4.17.21" }, "dependencies": { - "cssnano": "6.0.5", + "cssnano": "6.1.2", "execa": "8.0.1", "fast-glob": "3.3.2", "ignore-walk": "6.0.4", "js-yaml": "4.1.0", - "postcss": "8.4.35", - "tar": "6.2.0", - "terser": "5.28.1", - "typescript": "5.3.3" + "postcss": "8.4.38", + "tar": "6.2.1", + "terser": "5.30.3", + "typescript": "5.4.5", + "esbuild": "0.20.2", + "glob": "10.3.12" }, "devDependencies": { - "@typescript-eslint/eslint-plugin": "7.1.0", - "@typescript-eslint/parser": "7.1.0", + "@types/node": "20.12.7", + "@typescript-eslint/eslint-plugin": "7.7.1", + "@typescript-eslint/parser": "7.7.1", "cross-env": "7.0.3", - "cypress": "13.6.6", + "cypress": "13.7.3", "eslint": "8.57.0", "ncp": "2.0.0", "start-server-and-test": "2.0.3" diff --git a/packages/backend/.swcrc b/packages/backend/.swcrc index 0504a2d389..845190b5f4 100644 --- a/packages/backend/.swcrc +++ b/packages/backend/.swcrc @@ -19,5 +19,6 @@ }, "target": "es2022" }, - "minify": false + "minify": false, + "sourceMaps": "inline" } diff --git a/packages/backend/assets/redoc.html b/packages/backend/assets/redoc.html index 061608bf53..1b7ff9e0d2 100644 --- a/packages/backend/assets/redoc.html +++ b/packages/backend/assets/redoc.html @@ -19,6 +19,6 @@ - + diff --git a/packages/backend/generate_api_json.js b/packages/backend/generate_api_json.js deleted file mode 100644 index 4079b3bb0a..0000000000 --- a/packages/backend/generate_api_json.js +++ /dev/null @@ -1,8 +0,0 @@ -import { loadConfig } from './built/config.js' -import { genOpenapiSpec } from './built/server/api/openapi/gen-spec.js' -import { writeFileSync } from "node:fs"; - -const config = loadConfig(); -const spec = genOpenapiSpec(config, true); - -writeFileSync('./built/api.json', JSON.stringify(spec), 'utf-8'); \ No newline at end of file diff --git a/packages/backend/migration/1680969937000-larger-image-comment.js b/packages/backend/migration/1680969937000-larger-image-comment.js index b6b4f90913..2645b12630 100644 --- a/packages/backend/migration/1680969937000-larger-image-comment.js +++ b/packages/backend/migration/1680969937000-larger-image-comment.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: dakkar and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class largerImageComment1680969937000 { name = 'largerImageComment1680969937000'; diff --git a/packages/backend/migration/1682753227899-NoteEdit.js b/packages/backend/migration/1682753227899-NoteEdit.js index 55a0de0206..e67b1c566d 100644 --- a/packages/backend/migration/1682753227899-NoteEdit.js +++ b/packages/backend/migration/1682753227899-NoteEdit.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class NoteEdit1682753227899 { name = "NoteEdit1682753227899"; diff --git a/packages/backend/migration/1689325027964-UserBlacklistAnntena.js b/packages/backend/migration/1689325027964-UserBlacklistAnntena.js index ce246b20f8..2dc7774493 100644 --- a/packages/backend/migration/1689325027964-UserBlacklistAnntena.js +++ b/packages/backend/migration/1689325027964-UserBlacklistAnntena.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class UserBlacklistAnntena1689325027964 { name = 'UserBlacklistAnntena1689325027964' diff --git a/packages/backend/migration/1690417561185-fix-renote-muting.js b/packages/backend/migration/1690417561185-fix-renote-muting.js index 14150b0362..d9604ca26c 100644 --- a/packages/backend/migration/1690417561185-fix-renote-muting.js +++ b/packages/backend/migration/1690417561185-fix-renote-muting.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class FixRenoteMuting1690417561185 { name = 'FixRenoteMuting1690417561185' diff --git a/packages/backend/migration/1690417561186-ChangeCacheRemoteFilesDefault.js b/packages/backend/migration/1690417561186-ChangeCacheRemoteFilesDefault.js index 7eda5debe5..9bccdb3bb5 100644 --- a/packages/backend/migration/1690417561186-ChangeCacheRemoteFilesDefault.js +++ b/packages/backend/migration/1690417561186-ChangeCacheRemoteFilesDefault.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class ChangeCacheRemoteFilesDefault1690417561186 { name = 'ChangeCacheRemoteFilesDefault1690417561186' diff --git a/packages/backend/migration/1690417561187-Fix.js b/packages/backend/migration/1690417561187-Fix.js index e780e66d7b..7f1d62d68c 100644 --- a/packages/backend/migration/1690417561187-Fix.js +++ b/packages/backend/migration/1690417561187-Fix.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class Fix1690417561187 { name = 'Fix1690417561187' diff --git a/packages/backend/migration/1690569881926-user-2fa-backup-codes.js b/packages/backend/migration/1690569881926-user-2fa-backup-codes.js index 2049df8ea2..a3ef8dcf08 100644 --- a/packages/backend/migration/1690569881926-user-2fa-backup-codes.js +++ b/packages/backend/migration/1690569881926-user-2fa-backup-codes.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class User2faBackupCodes1690569881926 { name = 'User2faBackupCodes1690569881926' diff --git a/packages/backend/migration/1691264431000-add-lb-to-user.js b/packages/backend/migration/1691264431000-add-lb-to-user.js index fe6265e3f5..f06017468a 100644 --- a/packages/backend/migration/1691264431000-add-lb-to-user.js +++ b/packages/backend/migration/1691264431000-add-lb-to-user.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: amelia and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class AddLbToUser1691264431000 { name = "AddLbToUser1691264431000"; @@ -17,4 +22,4 @@ export class AddLbToUser1691264431000 { ALTER TABLE "user_profile" DROP COLUMN "listenbrainz" `); } -} \ No newline at end of file +} diff --git a/packages/backend/migration/1691649257651-refine-announcement.js b/packages/backend/migration/1691649257651-refine-announcement.js index d8d63f3103..ac621155d5 100644 --- a/packages/backend/migration/1691649257651-refine-announcement.js +++ b/packages/backend/migration/1691649257651-refine-announcement.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class RefineAnnouncement1691649257651 { name = 'RefineAnnouncement1691649257651' diff --git a/packages/backend/migration/1691657412740-refine-announcement-2.js b/packages/backend/migration/1691657412740-refine-announcement-2.js index 8791f99f44..67edf19659 100644 --- a/packages/backend/migration/1691657412740-refine-announcement-2.js +++ b/packages/backend/migration/1691657412740-refine-announcement-2.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class RefineAnnouncement21691657412740 { name = 'RefineAnnouncement21691657412740' diff --git a/packages/backend/migration/1695260774117-verified-links.js b/packages/backend/migration/1695260774117-verified-links.js index 18e0571d81..64c8a9ad8f 100644 --- a/packages/backend/migration/1695260774117-verified-links.js +++ b/packages/backend/migration/1695260774117-verified-links.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class VerifiedLinks1695260774117 { name = 'VerifiedLinks1695260774117' diff --git a/packages/backend/migration/1695288787870-following-notify.js b/packages/backend/migration/1695288787870-following-notify.js index e7e2194b15..b3f78d5f2a 100644 --- a/packages/backend/migration/1695288787870-following-notify.js +++ b/packages/backend/migration/1695288787870-following-notify.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class FollowingNotify1695288787870 { name = 'FollowingNotify1695288787870' diff --git a/packages/backend/migration/1695440131671-short-name.js b/packages/backend/migration/1695440131671-short-name.js index 2c37297fc1..fdc256caf8 100644 --- a/packages/backend/migration/1695440131671-short-name.js +++ b/packages/backend/migration/1695440131671-short-name.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class ShortName1695440131671 { name = 'ShortName1695440131671' diff --git a/packages/backend/migration/1695605508898-mutingNotificationTypes.js b/packages/backend/migration/1695605508898-mutingNotificationTypes.js index 8c0e52a2f0..67d4243142 100644 --- a/packages/backend/migration/1695605508898-mutingNotificationTypes.js +++ b/packages/backend/migration/1695605508898-mutingNotificationTypes.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class MutingNotificationTypes1695605508898 { name = 'MutingNotificationTypes1695605508898' diff --git a/packages/backend/migration/1695937489995-enableAchievements.js b/packages/backend/migration/1695937489995-enableAchievements.js index 2c20971ff5..1ee08de146 100644 --- a/packages/backend/migration/1695937489995-enableAchievements.js +++ b/packages/backend/migration/1695937489995-enableAchievements.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class EnableAchievements1695937489995 { name = 'EnableAchievements1695937489995' @@ -8,4 +13,4 @@ export class EnableAchievements1695937489995 { async down(queryRunner) { await queryRunner.query(`ALTER TABLE "meta" DROP COLUMN "enableAchievements"`); } -} \ No newline at end of file +} diff --git a/packages/backend/migration/1696323464251-user-list-membership.js b/packages/backend/migration/1696323464251-user-list-membership.js index 7534040c4c..dc1d438dd7 100644 --- a/packages/backend/migration/1696323464251-user-list-membership.js +++ b/packages/backend/migration/1696323464251-user-list-membership.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class UserListMembership1696323464251 { name = 'UserListMembership1696323464251' diff --git a/packages/backend/migration/1696331570827-hibernation.js b/packages/backend/migration/1696331570827-hibernation.js index 119d35913f..1487ece77c 100644 --- a/packages/backend/migration/1696331570827-hibernation.js +++ b/packages/backend/migration/1696331570827-hibernation.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class Hibernation1696331570827 { name = 'Hibernation1696331570827' diff --git a/packages/backend/migration/1696332072038-clean.js b/packages/backend/migration/1696332072038-clean.js index 2eecf70cff..3900b96328 100644 --- a/packages/backend/migration/1696332072038-clean.js +++ b/packages/backend/migration/1696332072038-clean.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class Clean1696332072038 { name = 'Clean1696332072038' diff --git a/packages/backend/migration/1696386694000-speakAsCat.js b/packages/backend/migration/1696386694000-speakAsCat.js index d68b9401bf..b9ba95e2fa 100644 --- a/packages/backend/migration/1696386694000-speakAsCat.js +++ b/packages/backend/migration/1696386694000-speakAsCat.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class SpeakAsCat1696386694000 { name = "SpeakAsCat1696386694000"; diff --git a/packages/backend/migration/1696548899000-background.js b/packages/backend/migration/1696548899000-background.js index 59309b98c2..f1c0b5a4a5 100644 --- a/packages/backend/migration/1696548899000-background.js +++ b/packages/backend/migration/1696548899000-background.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class Background1696548899000 { name = 'Background1696548899000' @@ -16,4 +21,4 @@ export class Background1696548899000 { await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "backgroundUrl"`); await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "backgroundBlurhash"`); } -} \ No newline at end of file +} diff --git a/packages/backend/migration/1697580470000-approvalSignup.js b/packages/backend/migration/1697580470000-approvalSignup.js index c5f8255d49..cc53a6bb5c 100644 --- a/packages/backend/migration/1697580470000-approvalSignup.js +++ b/packages/backend/migration/1697580470000-approvalSignup.js @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: syuilo and other misskey contributors + * SPDX-FileCopyrightText: marie and other Sharkey contributors * SPDX-License-Identifier: AGPL-3.0-only */ diff --git a/packages/backend/migration/1697603945000-BotTrending.js b/packages/backend/migration/1697603945000-BotTrending.js index 73f1f598ed..d59f1b0552 100644 --- a/packages/backend/migration/1697603945000-BotTrending.js +++ b/packages/backend/migration/1697603945000-BotTrending.js @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: syuilo and other misskey contributors + * SPDX-FileCopyrightText: marie and other Sharkey contributors * SPDX-License-Identifier: AGPL-3.0-only */ diff --git a/packages/backend/migration/1697624010000-isSilenced.js b/packages/backend/migration/1697624010000-isSilenced.js index 98b5e8c55c..16749b54cf 100644 --- a/packages/backend/migration/1697624010000-isSilenced.js +++ b/packages/backend/migration/1697624010000-isSilenced.js @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: syuilo and other misskey contributors + * SPDX-FileCopyrightText: marie and other Sharkey contributors * SPDX-License-Identifier: AGPL-3.0-only */ diff --git a/packages/backend/migration/1697970083000-alterNoteEdit.js b/packages/backend/migration/1697970083000-alterNoteEdit.js index 11accb3c54..0aa4f8fa9c 100644 --- a/packages/backend/migration/1697970083000-alterNoteEdit.js +++ b/packages/backend/migration/1697970083000-alterNoteEdit.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class AlterNoteEdit1697970083000 { name = "AlterNoteEdit1697970083000"; diff --git a/packages/backend/migration/1697970083001-oldDateNoteEdit.js b/packages/backend/migration/1697970083001-oldDateNoteEdit.js index 17565a0914..c21f62c486 100644 --- a/packages/backend/migration/1697970083001-oldDateNoteEdit.js +++ b/packages/backend/migration/1697970083001-oldDateNoteEdit.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class OldDateNoteEdit1697970083001 { name = "OldDateNoteEdit1697970083001"; diff --git a/packages/backend/migration/1699376974000-isIndexable.js b/packages/backend/migration/1699376974000-isIndexable.js index ae826924a8..7919b36c5d 100644 --- a/packages/backend/migration/1699376974000-isIndexable.js +++ b/packages/backend/migration/1699376974000-isIndexable.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class IsIndexable1699376974000 { name = 'IsIndexable1699376974000' diff --git a/packages/backend/migration/1699819257000-defaultLike.js b/packages/backend/migration/1699819257000-defaultLike.js index 45492fa6c6..a91926698a 100644 --- a/packages/backend/migration/1699819257000-defaultLike.js +++ b/packages/backend/migration/1699819257000-defaultLike.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class instanceDefaultLike1699819257000 { name = 'instanceDefaultLike1699819257000' diff --git a/packages/backend/migration/1700228972000-update-indexable.js b/packages/backend/migration/1700228972000-update-indexable.js index e724e2ec7e..1d46fd08fd 100644 --- a/packages/backend/migration/1700228972000-update-indexable.js +++ b/packages/backend/migration/1700228972000-update-indexable.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class UpdateIndexable1700228972000 { name = 'UpdateIndexable1700228972000' diff --git a/packages/backend/migration/1700383825690-hard-mute.js b/packages/backend/migration/1700383825690-hard-mute.js index afd3247f5c..92c3ada4a1 100644 --- a/packages/backend/migration/1700383825690-hard-mute.js +++ b/packages/backend/migration/1700383825690-hard-mute.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class HardMute1700383825690 { name = 'HardMute1700383825690' diff --git a/packages/backend/migration/1701647674000-BubbleInstances.js b/packages/backend/migration/1701647674000-BubbleInstances.js index 9928b4c36e..f048f521b0 100644 --- a/packages/backend/migration/1701647674000-BubbleInstances.js +++ b/packages/backend/migration/1701647674000-BubbleInstances.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class BubbleInstances1701647674000 { name = 'BubbleInstances1701647674000' diff --git a/packages/backend/migration/1701809447000-NSFW-Instance.js b/packages/backend/migration/1701809447000-NSFW-Instance.js index 882aa9865d..51075517b0 100644 --- a/packages/backend/migration/1701809447000-NSFW-Instance.js +++ b/packages/backend/migration/1701809447000-NSFW-Instance.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class NSFWInstance1701809447000 { name = 'NSFWInstance1701809447000' diff --git a/packages/backend/migration/1704744370000-add-donation-url.js b/packages/backend/migration/1704744370000-add-donation-url.js index c953b13cc9..ead22c6a95 100644 --- a/packages/backend/migration/1704744370000-add-donation-url.js +++ b/packages/backend/migration/1704744370000-add-donation-url.js @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: nila and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export class AddDonationUrl1704744370000 { name = 'AddDonationUrl1704744370000' diff --git a/packages/backend/migration/1706232992000-deeplx.js b/packages/backend/migration/1706232992000-deeplx.js index 5c763dbf8b..17ddbef26a 100644 --- a/packages/backend/migration/1706232992000-deeplx.js +++ b/packages/backend/migration/1706232992000-deeplx.js @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: syuilo and other misskey contributors + * SPDX-FileCopyrightText: marie and other Sharkey contributors * SPDX-License-Identifier: AGPL-3.0-only */ diff --git a/packages/backend/migration/1710512074000-url-preview-meta.js b/packages/backend/migration/1710512074000-url-preview-meta.js new file mode 100644 index 0000000000..8af521bbf4 --- /dev/null +++ b/packages/backend/migration/1710512074000-url-preview-meta.js @@ -0,0 +1,42 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class UrlPreviewMeta1710512074000 { + name = 'UrlPreviewMeta1710512074000' + + async up(queryRunner) { + await queryRunner.query(` + alter table meta + rename column "summalyProxy" to "urlPreviewSummaryProxyUrl"; + alter table meta + add "urlPreviewEnabled" boolean default true not null; + alter table meta + add "urlPreviewTimeout" integer default 10000 not null; + alter table meta + add "urlPreviewMaximumContentLength" bigint default 10485760 not null; + alter table meta + add "urlPreviewRequireContentLength" boolean default false not null; + alter table meta + add "urlPreviewUserAgent" varchar(1024) default null; + `); + } + + async down(queryRunner) { + await queryRunner.query(` + alter table meta + rename column "urlPreviewSummaryProxyUrl" to "summalyProxy"; + alter table meta + drop column "urlPreviewEnabled"; + alter table meta + drop column "urlPreviewTimeout"; + alter table meta + drop column "urlPreviewMaximumContentLength"; + alter table meta + drop column "urlPreviewRequireContentLength"; + alter table meta + drop column "urlPreviewUserAgent"; + `); + } +} diff --git a/packages/backend/migration/1710919614510-antenna-exclude-bots.js b/packages/backend/migration/1710919614510-antenna-exclude-bots.js new file mode 100644 index 0000000000..fac84317cc --- /dev/null +++ b/packages/backend/migration/1710919614510-antenna-exclude-bots.js @@ -0,0 +1,16 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class AntennaExcludeBots1710919614510 { + name = 'AntennaExcludeBots1710919614510' + + async up(queryRunner) { + await queryRunner.query(`ALTER TABLE "antenna" ADD "excludeBots" boolean NOT NULL DEFAULT false`); + } + + async down(queryRunner) { + await queryRunner.query(`ALTER TABLE "antenna" DROP COLUMN "excludeBots"`); + } +} diff --git a/packages/backend/migration/1716129964060-ChannelIdDenormalizedForMiPoll.js b/packages/backend/migration/1716129964060-ChannelIdDenormalizedForMiPoll.js new file mode 100644 index 0000000000..f736378c04 --- /dev/null +++ b/packages/backend/migration/1716129964060-ChannelIdDenormalizedForMiPoll.js @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class ChannelIdDenormalizedForMiPoll1716129964060 { + name = 'ChannelIdDenormalizedForMiPoll1716129964060' + + async up(queryRunner) { + await queryRunner.query(`ALTER TABLE "poll" ADD "channelId" character varying(32)`); + await queryRunner.query(`COMMENT ON COLUMN "poll"."channelId" IS '[Denormalized]'`); + await queryRunner.query(`CREATE INDEX "IDX_c1240fcc9675946ea5d6c2860e" ON "poll" ("channelId") `); + await queryRunner.query(`UPDATE "poll" SET "channelId" = "note"."channelId" FROM "note" WHERE "poll"."noteId" = "note"."id"`); + } + + async down(queryRunner) { + await queryRunner.query(`DROP INDEX "public"."IDX_c1240fcc9675946ea5d6c2860e"`); + await queryRunner.query(`COMMENT ON COLUMN "poll"."channelId" IS '[Denormalized]'`); + await queryRunner.query(`ALTER TABLE "poll" DROP COLUMN "channelId"`); + } +} diff --git a/packages/backend/migration/1716345015347-NotRespondingSince.js b/packages/backend/migration/1716345015347-NotRespondingSince.js new file mode 100644 index 0000000000..fc4ee6639a --- /dev/null +++ b/packages/backend/migration/1716345015347-NotRespondingSince.js @@ -0,0 +1,16 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class NotRespondingSince1716345015347 { + name = 'NotRespondingSince1716345015347' + + async up(queryRunner) { + await queryRunner.query(`ALTER TABLE "instance" ADD "notRespondingSince" TIMESTAMP WITH TIME ZONE`); + } + + async down(queryRunner) { + await queryRunner.query(`ALTER TABLE "instance" DROP COLUMN "notRespondingSince"`); + } +} diff --git a/packages/backend/migration/1716447138870-SuspensionStateInsteadOfIsSspended.js b/packages/backend/migration/1716447138870-SuspensionStateInsteadOfIsSspended.js new file mode 100644 index 0000000000..4808a9a3db --- /dev/null +++ b/packages/backend/migration/1716447138870-SuspensionStateInsteadOfIsSspended.js @@ -0,0 +1,50 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class SuspensionStateInsteadOfIsSspended1716345771510 { + name = 'SuspensionStateInsteadOfIsSspended1716345771510' + + async up(queryRunner) { + await queryRunner.query(`CREATE TYPE "public"."instance_suspensionstate_enum" AS ENUM('none', 'manuallySuspended', 'goneSuspended', 'autoSuspendedForNotResponding')`); + + await queryRunner.query(`DROP INDEX "public"."IDX_34500da2e38ac393f7bb6b299c"`); + + await queryRunner.query(`ALTER TABLE "instance" RENAME COLUMN "isSuspended" TO "suspensionState"`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" DROP DEFAULT`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" TYPE "public"."instance_suspensionstate_enum" USING ( + CASE "suspensionState" + WHEN TRUE THEN 'manuallySuspended'::instance_suspensionstate_enum + ELSE 'none'::instance_suspensionstate_enum + END + )`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" SET DEFAULT 'none'`); + + await queryRunner.query(`CREATE INDEX "IDX_3ede46f507c87ad698051d56a8" ON "instance" ("suspensionState") `); + } + + async down(queryRunner) { + await queryRunner.query(`DROP INDEX "public"."IDX_3ede46f507c87ad698051d56a8"`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" DROP DEFAULT`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" TYPE boolean USING ( + CASE "suspensionState" + WHEN 'none'::instance_suspensionstate_enum THEN FALSE + ELSE TRUE + END + )`); + + await queryRunner.query(`ALTER TABLE "instance" ALTER COLUMN "suspensionState" SET DEFAULT false`); + + await queryRunner.query(`ALTER TABLE "instance" RENAME COLUMN "suspensionState" TO "isSuspended"`); + + await queryRunner.query(`CREATE INDEX "IDX_34500da2e38ac393f7bb6b299c" ON "instance" ("isSuspended") `); + + await queryRunner.query(`DROP TYPE "public"."instance_suspensionstate_enum"`); + } +} diff --git a/packages/backend/migration/1716450883149-RemoveAntennaNotify.js b/packages/backend/migration/1716450883149-RemoveAntennaNotify.js new file mode 100644 index 0000000000..b5a2441855 --- /dev/null +++ b/packages/backend/migration/1716450883149-RemoveAntennaNotify.js @@ -0,0 +1,16 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class RemoveAntennaNotify1716450883149 { + name = 'RemoveAntennaNotify1716450883149' + + async up(queryRunner) { + await queryRunner.query(`ALTER TABLE "antenna" DROP COLUMN "notify"`); + } + + async down(queryRunner) { + await queryRunner.query(`ALTER TABLE "antenna" ADD "notify" boolean NOT NULL`); + } +} diff --git a/packages/backend/migration/1717117195275-inquiryUrl.js b/packages/backend/migration/1717117195275-inquiryUrl.js new file mode 100644 index 0000000000..29ca31af14 --- /dev/null +++ b/packages/backend/migration/1717117195275-inquiryUrl.js @@ -0,0 +1,16 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class InquiryUrl1717117195275 { + name = 'InquiryUrl1717117195275' + + async up(queryRunner) { + await queryRunner.query(`ALTER TABLE "meta" ADD "inquiryUrl" character varying(1024)`); + } + + async down(queryRunner) { + await queryRunner.query(`ALTER TABLE "meta" DROP COLUMN "inquiryUrl"`); + } +} diff --git a/packages/backend/package.json b/packages/backend/package.json index 2091ccf618..b05dc10c11 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -4,22 +4,22 @@ "private": true, "type": "module", "engines": { - "node": ">=20.10.0" + "node": "^20.10.0" }, "scripts": { "start": "node ./built/boot/entry.js", "start:test": "cross-env NODE_ENV=test node ./built/boot/entry.js", "migrate": "pnpm typeorm migration:run -d ormconfig.js", "revert": "pnpm typeorm migration:revert -d ormconfig.js", - "check:connect": "node ./check_connect.js", - "build": "swc src -d built -D", - "build:test": "swc test-server -d built-test -D --config-file test-server/.swcrc", - "watch:swc": "swc src -d built -D -w", + "check:connect": "node ./scripts/check_connect.js", + "build": "swc src -d built -D --strip-leading-paths", + "build:test": "swc test-server -d built-test -D --config-file test-server/.swcrc --strip-leading-paths", + "watch:swc": "swc src -d built -D -w --strip-leading-paths", "build:tsc": "tsc -p tsconfig.json && tsc-alias -p tsconfig.json", - "watch": "node watch.mjs", + "watch": "node ./scripts/watch.mjs", "restart": "pnpm build && pnpm start", - "dev": "nodemon -w src -e ts,js,mjs,cjs,json --exec \"cross-env NODE_ENV=development pnpm run restart\"", - "typecheck": "pnpm --filter megalodon build && tsc --noEmit", + "dev": "node ./scripts/dev.mjs", + "typecheck": "pnpm --filter megalodon build && tsc --noEmit && tsc -p test --noEmit", "eslint": "eslint --quiet \"src/**/*.ts\"", "lint": "pnpm typecheck && pnpm eslint", "jest": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --forceExit --config jest.config.unit.cjs", @@ -31,7 +31,7 @@ "test:e2e": "pnpm build && pnpm build:test && pnpm jest:e2e", "test-and-coverage": "pnpm jest-and-coverage", "test-and-coverage:e2e": "pnpm build && pnpm build:test && pnpm jest-and-coverage:e2e", - "generate-api-json": "pnpm build && node ./generate_api_json.js" + "generate-api-json": "pnpm build && node ./scripts/generate_api_json.js" }, "optionalDependencies": { "@swc/core-android-arm64": "1.3.11", @@ -65,40 +65,43 @@ "dependencies": { "@aws-sdk/client-s3": "3.412.0", "@aws-sdk/lib-storage": "3.412.0", - "@bull-board/api": "5.14.2", - "@bull-board/fastify": "5.14.2", - "@bull-board/ui": "5.14.2", - "@discordapp/twemoji": "15.0.2", + "@bull-board/api": "5.17.0", + "@bull-board/fastify": "5.17.0", + "@bull-board/ui": "5.17.0", + "@discordapp/twemoji": "15.0.3", "@fastify/accepts": "4.3.0", "@fastify/cookie": "9.3.1", - "@fastify/cors": "8.5.0", - "@fastify/express": "2.3.0", - "@fastify/http-proxy": "9.3.0", - "@fastify/multipart": "8.1.0", - "@fastify/static": "6.12.0", - "@fastify/view": "8.2.0", + "@fastify/cors": "9.0.1", + "@fastify/express": "3.0.0", + "@fastify/http-proxy": "9.5.0", + "@fastify/multipart": "8.2.0", + "@fastify/static": "7.0.3", + "@fastify/view": "9.1.0", "@misskey-dev/sharp-read-bmp": "1.2.0", - "@misskey-dev/summaly": "5.0.3", - "@nestjs/common": "10.3.3", - "@nestjs/core": "10.3.3", - "@nestjs/testing": "10.3.3", + "@misskey-dev/summaly": "5.1.0", + "@napi-rs/canvas": "^0.1.52", + "@nestjs/common": "10.3.8", + "@nestjs/core": "10.3.8", + "@nestjs/testing": "10.3.8", "@peertube/http-signature": "1.7.0", - "@simplewebauthn/server": "9.0.3", + "@sentry/node": "^8.5.0", + "@sentry/profiling-node": "^8.5.0", + "@simplewebauthn/server": "10.0.0", "@sinonjs/fake-timers": "11.2.2", - "@smithy/node-http-handler": "2.1.10", - "@swc/cli": "0.1.63", - "@swc/core": "1.3.107", + "@smithy/node-http-handler": "2.5.0", + "@swc/cli": "0.3.12", + "@swc/core": "1.4.17", "@transfem-org/sfm-js": "0.24.5", - "@twemoji/parser": "15.0.0", + "@twemoji/parser": "15.1.1", "accepts": "1.3.8", - "ajv": "8.12.0", - "archiver": "6.0.1", + "ajv": "8.13.0", + "archiver": "7.0.1", "argon2": "^0.40.1", - "async-mutex": "0.4.1", + "async-mutex": "0.5.0", "bcryptjs": "2.4.3", "blurhash": "2.0.5", "body-parser": "1.20.2", - "bullmq": "5.4.0", + "bullmq": "5.7.8", "cacheable-lookup": "7.0.0", "cbor": "9.0.2", "chalk": "5.3.0", @@ -109,7 +112,7 @@ "content-disposition": "0.5.4", "date-fns": "2.30.0", "deep-email-validator": "0.1.21", - "fastify": "4.25.2", + "fastify": "4.26.2", "fastify-multer": "^2.0.3", "fastify-raw-body": "4.3.0", "feed": "4.2.2", @@ -117,79 +120,78 @@ "fluent-ffmpeg": "2.1.2", "form-data": "4.0.0", "glob": "10.3.10", - "got": "14.2.0", + "got": "14.2.1", "happy-dom": "10.0.3", "hpagent": "1.2.0", "htmlescape": "1.1.1", - "http-link-header": "1.1.2", - "ioredis": "5.3.2", + "http-link-header": "1.1.3", + "ioredis": "5.4.1", "ip-cidr": "3.1.0", - "ipaddr.js": "2.1.0", + "ipaddr.js": "2.2.0", "is-svg": "5.0.0", "js-yaml": "4.1.0", - "jsdom": "23.2.0", + "jsdom": "24.0.0", "json5": "2.2.3", "jsonld": "8.3.2", "jsrsasign": "11.1.0", "megalodon": "workspace:*", - "meilisearch": "0.37.0", + "meilisearch": "0.38.0", "microformats-parser": "2.0.2", "mime-types": "2.1.35", "misskey-js": "workspace:*", "misskey-reversi": "workspace:*", "ms": "3.0.0-canary.1", - "nanoid": "5.0.6", + "nanoid": "5.0.7", "nested-property": "4.0.0", "node-fetch": "3.3.2", - "nodemailer": "6.9.10", + "nodemailer": "6.9.13", "oauth": "0.10.0", "oauth2orize": "1.12.0", "oauth2orize-pkce": "0.1.2", "os-utils": "0.0.14", - "otpauth": "9.2.2", + "otpauth": "9.2.3", "parse5": "7.1.2", - "pg": "8.11.3", + "pg": "8.11.5", "pkce-challenge": "4.1.0", "probe-image-size": "7.2.3", "promise-limit": "2.7.0", "pug": "3.0.2", "punycode": "2.3.1", - "pureimage": "0.3.17", "qrcode": "1.5.3", "random-seed": "0.3.0", "ratelimiter": "3.4.1", - "re2": "1.20.9", + "re2": "1.20.10", "redis-lock": "0.1.4", - "reflect-metadata": "0.2.1", + "reflect-metadata": "0.2.2", "rename": "1.0.4", "rss-parser": "3.13.0", "rxjs": "7.8.1", - "sanitize-html": "2.12.1", + "sanitize-html": "2.13.0", "secure-json-parse": "2.7.0", - "sharp": "0.33.2", + "sharp": "0.33.3", "slacc": "0.0.10", "strict-event-emitter-types": "2.0.0", "stringz": "2.1.0", - "systeminformation": "5.22.0", + "systeminformation": "5.22.7", "tinycolor2": "1.6.0", "tmp": "0.2.3", "tsc-alias": "1.8.8", "tsconfig-paths": "4.2.0", "typeorm": "0.3.20", - "typescript": "5.3.3", + "typescript": "5.4.5", "ulid": "2.3.0", "uuid": "^9.0.1", "vary": "1.1.2", "web-push": "3.6.7", - "ws": "8.16.0", + "ws": "8.17.0", "xev": "3.0.2" }, "devDependencies": { "@jest/globals": "29.7.0", "@misskey-dev/eslint-plugin": "1.0.0", - "@nestjs/platform-express": "10.3.3", - "@simplewebauthn/types": "9.0.1", - "@swc/jest": "0.2.31", + "@nestjs/platform-express": "10.3.8", + "@simplewebauthn/types": "10.0.0", + "@swc/jest": "0.2.36", "@types/accepts": "1.3.7", "@types/archiver": "6.0.2", "@types/bcryptjs": "2.4.6", @@ -199,20 +201,20 @@ "@types/fluent-ffmpeg": "2.1.24", "@types/htmlescape": "^1.1.3", "@types/http-link-header": "1.0.5", - "@types/jest": "29.5.11", + "@types/jest": "29.5.12", "@types/js-yaml": "4.0.9", "@types/jsdom": "21.1.6", "@types/jsonld": "1.5.13", - "@types/jsrsasign": "10.5.12", + "@types/jsrsasign": "10.5.14", "@types/mime-types": "2.1.4", "@types/ms": "0.7.34", - "@types/node": "20.11.22", + "@types/node": "20.12.7", "@types/node-fetch": "3.0.3", - "@types/nodemailer": "6.4.14", + "@types/nodemailer": "6.4.15", "@types/oauth": "0.9.4", - "@types/oauth2orize": "1.11.3", + "@types/oauth2orize": "1.11.5", "@types/oauth2orize-pkce": "0.1.2", - "@types/pg": "8.11.2", + "@types/pg": "8.11.5", "@types/pug": "2.0.10", "@types/punycode": "2.1.4", "@types/qrcode": "1.5.5", @@ -229,8 +231,8 @@ "@types/vary": "1.1.3", "@types/web-push": "3.6.3", "@types/ws": "8.5.10", - "@typescript-eslint/eslint-plugin": "7.1.0", - "@typescript-eslint/parser": "7.1.0", + "@typescript-eslint/eslint-plugin": "7.7.1", + "@typescript-eslint/parser": "7.7.1", "aws-sdk-client-mock": "3.0.1", "cross-env": "7.0.3", "eslint": "8.57.0", diff --git a/packages/backend/check_connect.js b/packages/backend/scripts/check_connect.js similarity index 85% rename from packages/backend/check_connect.js rename to packages/backend/scripts/check_connect.js index d88e649c09..ba25fd416c 100644 --- a/packages/backend/check_connect.js +++ b/packages/backend/scripts/check_connect.js @@ -4,7 +4,7 @@ */ import Redis from 'ioredis'; -import { loadConfig } from './built/config.js'; +import { loadConfig } from '../built/config.js'; const config = loadConfig(); const redis = new Redis(config.redis); diff --git a/packages/backend/scripts/dev.mjs b/packages/backend/scripts/dev.mjs new file mode 100644 index 0000000000..2d0de0f916 --- /dev/null +++ b/packages/backend/scripts/dev.mjs @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { execa, execaNode } from 'execa'; + +/** @type {import('execa').ExecaChildProcess | undefined} */ +let backendProcess; + +async function execBuildAssets() { + await execa('pnpm', ['run', 'build-assets'], { + cwd: '../../', + stdout: process.stdout, + stderr: process.stderr, + }) +} + +function execStart() { + // pnpm run start を呼び出したいが、windowsだとプロセスグループ単位でのkillが出来ずゾンビプロセス化するので + // 上記と同等の動きをするコマンドで子・孫プロセスを作らないようにしたい + backendProcess = execaNode('./built/boot/entry.js', [], { + stdout: process.stdout, + stderr: process.stderr, + env: { + 'NODE_ENV': 'development', + }, + }); +} + +async function killProc() { + if (backendProcess) { + backendProcess.kill(); + await new Promise(resolve => backendProcess.on('exit', resolve)); + backendProcess = undefined; + } +} + +(async () => { + execaNode( + './node_modules/nodemon/bin/nodemon.js', + [ + '-w', 'src', + '-e', 'ts,js,mjs,cjs,json', + '--exec', 'pnpm', 'run', 'build', + ], + { + stdio: [process.stdin, process.stdout, process.stderr, 'ipc'], + }) + .on('message', async (message) => { + if (message.type === 'exit') { + // かならずbuild->build-assetsの順番で呼び出したいので、 + // 少々トリッキーだがnodemonからのexitイベントを利用してbuild-assets->startを行う。 + // pnpm restartをbuildが終わる前にbuild-assetsが動いてしまうので、バラバラに呼び出す必要がある + + await killProc(); + await execBuildAssets(); + execStart(); + } + }) +})(); diff --git a/packages/backend/scripts/generate_api_json.js b/packages/backend/scripts/generate_api_json.js new file mode 100644 index 0000000000..b4769ef801 --- /dev/null +++ b/packages/backend/scripts/generate_api_json.js @@ -0,0 +1,13 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { loadConfig } from '../built/config.js' +import { genOpenapiSpec } from '../built/server/api/openapi/gen-spec.js' +import { writeFileSync } from "node:fs"; + +const config = loadConfig(); +const spec = genOpenapiSpec(config, true); + +writeFileSync('./built/api.json', JSON.stringify(spec), 'utf-8'); diff --git a/packages/backend/watch.mjs b/packages/backend/scripts/watch.mjs similarity index 100% rename from packages/backend/watch.mjs rename to packages/backend/scripts/watch.mjs diff --git a/packages/backend/src/boot/entry.ts b/packages/backend/src/boot/entry.ts index 3882686fdc..d1744b4b4b 100644 --- a/packages/backend/src/boot/entry.ts +++ b/packages/backend/src/boot/entry.ts @@ -15,6 +15,7 @@ import Logger from '@/logger.js'; import { envOption } from '../env.js'; import { masterMain } from './master.js'; import { workerMain } from './worker.js'; +import { readyRef } from './ready.js'; import 'reflect-metadata'; @@ -79,6 +80,8 @@ async function main() { await workerMain(); } + readyRef.value = true; + // ユニットテスト時にMisskeyが子プロセスで起動された時のため // それ以外のときは process.send は使えないので弾く if (process.send) { diff --git a/packages/backend/src/boot/master.ts b/packages/backend/src/boot/master.ts index aafd43beea..303ba94207 100644 --- a/packages/backend/src/boot/master.ts +++ b/packages/backend/src/boot/master.ts @@ -10,6 +10,8 @@ import * as os from 'node:os'; import cluster from 'node:cluster'; import chalk from 'chalk'; import chalkTemplate from 'chalk-template'; +import * as Sentry from '@sentry/node'; +import { nodeProfilingIntegration } from '@sentry/profiling-node'; import Logger from '@/logger.js'; import { loadConfig } from '@/config.js'; import type { Config } from '@/config.js'; @@ -74,6 +76,24 @@ export async function masterMain() { bootLogger.succ('Sharkey initialized'); + if (config.sentryForBackend) { + Sentry.init({ + integrations: [ + ...(config.sentryForBackend.enableNodeProfiling ? [nodeProfilingIntegration()] : []), + ], + + // Performance Monitoring + tracesSampleRate: 1.0, // Capture 100% of the transactions + + // Set sampling rate for profiling - this is relative to tracesSampleRate + profilesSampleRate: 1.0, + + maxBreadcrumbs: 0, + + ...config.sentryForBackend.options, + }); + } + if (envOption.disableClustering) { if (envOption.onlyServer) { await server(); diff --git a/packages/backend/src/boot/ready.ts b/packages/backend/src/boot/ready.ts new file mode 100644 index 0000000000..591ae5cb58 --- /dev/null +++ b/packages/backend/src/boot/ready.ts @@ -0,0 +1,6 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export const readyRef = { value: false }; diff --git a/packages/backend/src/config.ts b/packages/backend/src/config.ts index 250b5c0536..58c4d028aa 100644 --- a/packages/backend/src/config.ts +++ b/packages/backend/src/config.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url'; import { dirname, resolve } from 'node:path'; import * as yaml from 'js-yaml'; import { globSync } from 'glob'; +import * as Sentry from '@sentry/node'; import type { RedisOptions } from 'ioredis'; type RedisOptionsSource = Partial & { @@ -57,6 +58,8 @@ type Source = { index: string; scope?: 'local' | 'global' | string[]; }; + sentryForBackend?: { options: Partial; enableNodeProfiling: boolean; }; + sentryForFrontend?: { options: Partial }; publishTarballInsteadOfProvideRepositoryUrl?: boolean; @@ -180,6 +183,8 @@ export type Config = { redisForPubsub: RedisOptions & RedisOptionsSource; redisForJobQueue: RedisOptions & RedisOptionsSource; redisForTimelines: RedisOptions & RedisOptionsSource; + sentryForBackend: { options: Partial; enableNodeProfiling: boolean; } | undefined; + sentryForFrontend: { options: Partial } | undefined; perChannelMaxNoteCacheCount: number; perUserNotificationsMaxCount: number; deactivateAntennaThreshold: number; @@ -263,6 +268,8 @@ export function loadConfig(): Config { redisForPubsub: config.redisForPubsub ? convertRedisOptions(config.redisForPubsub, host) : redis, redisForJobQueue: config.redisForJobQueue ? convertRedisOptions(config.redisForJobQueue, host) : redis, redisForTimelines: config.redisForTimelines ? convertRedisOptions(config.redisForTimelines, host) : redis, + sentryForBackend: config.sentryForBackend, + sentryForFrontend: config.sentryForFrontend, id: config.id, proxy: config.proxy, proxySmtp: config.proxySmtp, @@ -377,13 +384,13 @@ function applyEnvOverrides(config: Source) { } function _step2name(step: string|number): string { - return step.toString().replaceAll(/[^a-z0-9]+/gi,'').toUpperCase(); + return step.toString().replaceAll(/[^a-z0-9]+/gi, '').toUpperCase(); } // this recurses down, bailing out if there's no config to override function _descend(name: string, path: (string | number)[], thisStep: string | number, steps: (string | string[] | number | number[])[]) { name = `${name}${_step2name(thisStep)}_`; - path = [ ...path, thisStep ]; + path = [...path, thisStep]; _walk(name, path, steps); } @@ -393,7 +400,7 @@ function applyEnvOverrides(config: Source) { name = `MK_CONFIG_${name}${_step2name(lastStep)}`; const val = process.env[name]; - if (val != null && val != undefined) { + if (val !== null && val !== undefined) { _assign(path, lastStep, val); } @@ -434,9 +441,11 @@ function applyEnvOverrides(config: Source) { _apply_top(['dbSlaves', Array.from((config.dbSlaves ?? []).keys()), ['host', 'port', 'db', 'user', 'pass']]); _apply_top([ ['redis', 'redisForPubsub', 'redisForJobQueue', 'redisForTimelines'], - ['host','port','username','pass','db','prefix'], + ['host', 'port', 'username', 'pass', 'db', 'prefix'], ]); _apply_top(['meilisearch', ['host', 'port', 'apikey', 'ssl', 'index', 'scope']]); + _apply_top([['sentryForFrontend', 'sentryForBackend'], 'options', ['dsn', 'profileSampleRate', 'serverName', 'includeLocalVariables', 'proxy', 'keepAlive', 'caCerts']]); + _apply_top(['sentryForBackend', 'enableNodeProfiling']); _apply_top([['clusterLimit', 'deliverJobConcurrency', 'inboxJobConcurrency', 'relashionshipJobConcurrency', 'deliverJobPerSec', 'inboxJobPerSec', 'relashionshipJobPerSec', 'deliverJobMaxAttempts', 'inboxJobMaxAttempts']]); _apply_top([['outgoingAddress', 'outgoingAddressFamily', 'proxy', 'proxySmtp', 'mediaProxy', 'videoThumbnailGenerator']]); _apply_top([['maxFileSize', 'maxNoteLength', 'pidFile']]); diff --git a/packages/backend/src/core/AccountMoveService.ts b/packages/backend/src/core/AccountMoveService.ts index 5bd885df40..b6b591d240 100644 --- a/packages/backend/src/core/AccountMoveService.ts +++ b/packages/backend/src/core/AccountMoveService.ts @@ -305,7 +305,7 @@ export class AccountMoveService { let resultUser: MiLocalUser | MiRemoteUser | null = null; if (this.userEntityService.isRemoteUser(dst)) { - if ((new Date()).getTime() - (dst.lastFetchedAt?.getTime() ?? 0) > 10 * 1000) { + if (Date.now() - (dst.lastFetchedAt?.getTime() ?? 0) > 10 * 1000) { await this.apPersonService.updatePerson(dst.uri); } dst = await this.apPersonService.fetchPerson(dst.uri) ?? dst; @@ -321,7 +321,7 @@ export class AccountMoveService { if (!src) continue; // oldAccountを探してもこのサーバーに存在しない場合はフォロー関係もないということなのでスルー if (this.userEntityService.isRemoteUser(dst)) { - if ((new Date()).getTime() - (src.lastFetchedAt?.getTime() ?? 0) > 10 * 1000) { + if (Date.now() - (src.lastFetchedAt?.getTime() ?? 0) > 10 * 1000) { await this.apPersonService.updatePerson(srcUri); } diff --git a/packages/backend/src/core/AnnouncementService.ts b/packages/backend/src/core/AnnouncementService.ts index b298a70929..9b60df2cae 100644 --- a/packages/backend/src/core/AnnouncementService.ts +++ b/packages/backend/src/core/AnnouncementService.ts @@ -4,13 +4,14 @@ */ import { Inject, Injectable } from '@nestjs/common'; -import { Brackets } from 'typeorm'; +import { Brackets, EntityNotFoundError } from 'typeorm'; import { DI } from '@/di-symbols.js'; import type { MiUser } from '@/models/User.js'; import type { AnnouncementReadsRepository, AnnouncementsRepository, MiAnnouncement, MiAnnouncementRead, UsersRepository } from '@/models/_.js'; import { bindThis } from '@/decorators.js'; import { Packed } from '@/misc/json-schema.js'; import { IdService } from '@/core/IdService.js'; +import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js'; import { GlobalEventService } from '@/core/GlobalEventService.js'; import { ModerationLogService } from '@/core/ModerationLogService.js'; @@ -29,6 +30,7 @@ export class AnnouncementService { private idService: IdService, private globalEventService: GlobalEventService, private moderationLogService: ModerationLogService, + private announcementEntityService: AnnouncementEntityService, ) { } @@ -79,7 +81,7 @@ export class AnnouncementService { userId: values.userId, }).then(x => this.announcementsRepository.findOneByOrFail(x.identifiers[0])); - const packed = (await this.packMany([announcement]))[0]; + const packed = await this.announcementEntityService.pack(announcement); if (values.userId) { this.globalEventService.publishMainStream(values.userId, 'announcementCreated', { @@ -177,6 +179,24 @@ export class AnnouncementService { } } + @bindThis + public async getAnnouncement(announcementId: MiAnnouncement['id'], me: MiUser | null): Promise> { + const announcement = await this.announcementsRepository.findOneByOrFail({ id: announcementId }); + if (me) { + if (announcement.userId && announcement.userId !== me.id) { + throw new EntityNotFoundError(this.announcementsRepository.metadata.target, { id: announcementId }); + } + + const read = await this.announcementReadsRepository.findOneBy({ + announcementId: announcement.id, + userId: me.id, + }); + return this.announcementEntityService.pack({ ...announcement, isRead: read !== null }, me); + } else { + return this.announcementEntityService.pack(announcement, null); + } + } + @bindThis public async read(user: MiUser, announcementId: MiAnnouncement['id']): Promise { try { @@ -193,29 +213,4 @@ export class AnnouncementService { this.globalEventService.publishMainStream(user.id, 'readAllAnnouncements'); } } - - @bindThis - public async packMany( - announcements: MiAnnouncement[], - me?: { id: MiUser['id'] } | null | undefined, - options?: { - reads?: MiAnnouncementRead[]; - }, - ): Promise[]> { - const reads = me ? (options?.reads ?? await this.getReads(me.id)) : []; - return announcements.map(announcement => ({ - id: announcement.id, - createdAt: this.idService.parse(announcement.id).date.toISOString(), - updatedAt: announcement.updatedAt?.toISOString() ?? null, - text: announcement.text, - title: announcement.title, - imageUrl: announcement.imageUrl, - icon: announcement.icon, - display: announcement.display, - needConfirmationToRead: announcement.needConfirmationToRead, - silence: announcement.silence, - forYou: announcement.userId === me?.id, - isRead: reads.some(read => read.announcementId === announcement.id), - })); - } } diff --git a/packages/backend/src/core/AntennaService.ts b/packages/backend/src/core/AntennaService.ts index 5168b6576f..89e475b5f1 100644 --- a/packages/backend/src/core/AntennaService.ts +++ b/packages/backend/src/core/AntennaService.ts @@ -92,7 +92,7 @@ export class AntennaService implements OnApplicationShutdown { } @bindThis - public async addNoteToAntennas(note: MiNote, noteUser: { id: MiUser['id']; username: string; host: string | null; }): Promise { + public async addNoteToAntennas(note: MiNote, noteUser: { id: MiUser['id']; username: string; host: string | null; isBot: boolean; }): Promise { const antennas = await this.getAntennas(); const antennasWithMatchResult = await Promise.all(antennas.map(antenna => this.checkHitAntenna(antenna, note, noteUser).then(hit => [antenna, hit] as const))); const matchedAntennas = antennasWithMatchResult.filter(([, hit]) => hit).map(([antenna]) => antenna); @@ -110,10 +110,12 @@ export class AntennaService implements OnApplicationShutdown { // NOTE: フォローしているユーザーのノート、リストのユーザーのノート、グループのユーザーのノート指定はパフォーマンス上の理由で無効になっている @bindThis - public async checkHitAntenna(antenna: MiAntenna, note: (MiNote | Packed<'Note'>), noteUser: { id: MiUser['id']; username: string; host: string | null; }): Promise { + public async checkHitAntenna(antenna: MiAntenna, note: (MiNote | Packed<'Note'>), noteUser: { id: MiUser['id']; username: string; host: string | null; isBot: boolean; }): Promise { if (note.visibility === 'specified') return false; if (note.visibility === 'followers') return false; + if (antenna.excludeBots && noteUser.isBot) return false; + if (antenna.localOnly && noteUser.host != null) return false; if (!antenna.withReplies && note.replyId != null) return false; diff --git a/packages/backend/src/core/ChannelFollowingService.ts b/packages/backend/src/core/ChannelFollowingService.ts index 75843b9773..12251595e2 100644 --- a/packages/backend/src/core/ChannelFollowingService.ts +++ b/packages/backend/src/core/ChannelFollowingService.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable, OnModuleInit } from '@nestjs/common'; import Redis from 'ioredis'; import { DI } from '@/di-symbols.js'; diff --git a/packages/backend/src/core/CoreModule.ts b/packages/backend/src/core/CoreModule.ts index 48a2a2b80c..9baec9a59f 100644 --- a/packages/backend/src/core/CoreModule.ts +++ b/packages/backend/src/core/CoreModule.ts @@ -84,6 +84,7 @@ import ApRequestChart from './chart/charts/ap-request.js'; import { ChartManagementService } from './chart/ChartManagementService.js'; import { AbuseUserReportEntityService } from './entities/AbuseUserReportEntityService.js'; +import { AnnouncementEntityService } from './entities/AnnouncementEntityService.js'; import { AntennaEntityService } from './entities/AntennaEntityService.js'; import { AppEntityService } from './entities/AppEntityService.js'; import { AuthSessionEntityService } from './entities/AuthSessionEntityService.js'; @@ -127,7 +128,7 @@ import { ApMfmService } from './activitypub/ApMfmService.js'; import { ApRendererService } from './activitypub/ApRendererService.js'; import { ApRequestService } from './activitypub/ApRequestService.js'; import { ApResolverService } from './activitypub/ApResolverService.js'; -import { LdSignatureService } from './activitypub/LdSignatureService.js'; +import { JsonLdService } from './activitypub/JsonLdService.js'; import { RemoteLoggerService } from './RemoteLoggerService.js'; import { RemoteUserResolveService } from './RemoteUserResolveService.js'; import { WebfingerService } from './WebfingerService.js'; @@ -223,6 +224,7 @@ const $ApRequestChart: Provider = { provide: 'ApRequestChart', useExisting: ApRe const $ChartManagementService: Provider = { provide: 'ChartManagementService', useExisting: ChartManagementService }; const $AbuseUserReportEntityService: Provider = { provide: 'AbuseUserReportEntityService', useExisting: AbuseUserReportEntityService }; +const $AnnouncementEntityService: Provider = { provide: 'AnnouncementEntityService', useExisting: AnnouncementEntityService }; const $AntennaEntityService: Provider = { provide: 'AntennaEntityService', useExisting: AntennaEntityService }; const $AppEntityService: Provider = { provide: 'AppEntityService', useExisting: AppEntityService }; const $AuthSessionEntityService: Provider = { provide: 'AuthSessionEntityService', useExisting: AuthSessionEntityService }; @@ -266,7 +268,7 @@ const $ApMfmService: Provider = { provide: 'ApMfmService', useExisting: ApMfmSer const $ApRendererService: Provider = { provide: 'ApRendererService', useExisting: ApRendererService }; const $ApRequestService: Provider = { provide: 'ApRequestService', useExisting: ApRequestService }; const $ApResolverService: Provider = { provide: 'ApResolverService', useExisting: ApResolverService }; -const $LdSignatureService: Provider = { provide: 'LdSignatureService', useExisting: LdSignatureService }; +const $JsonLdService: Provider = { provide: 'JsonLdService', useExisting: JsonLdService }; const $RemoteLoggerService: Provider = { provide: 'RemoteLoggerService', useExisting: RemoteLoggerService }; const $RemoteUserResolveService: Provider = { provide: 'RemoteUserResolveService', useExisting: RemoteUserResolveService }; const $WebfingerService: Provider = { provide: 'WebfingerService', useExisting: WebfingerService }; @@ -363,6 +365,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ChartManagementService, AbuseUserReportEntityService, + AnnouncementEntityService, AntennaEntityService, AppEntityService, AuthSessionEntityService, @@ -406,7 +409,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ApRendererService, ApRequestService, ApResolverService, - LdSignatureService, + JsonLdService, RemoteLoggerService, RemoteUserResolveService, WebfingerService, @@ -499,6 +502,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting $ChartManagementService, $AbuseUserReportEntityService, + $AnnouncementEntityService, $AntennaEntityService, $AppEntityService, $AuthSessionEntityService, @@ -542,7 +546,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting $ApRendererService, $ApRequestService, $ApResolverService, - $LdSignatureService, + $JsonLdService, $RemoteLoggerService, $RemoteUserResolveService, $WebfingerService, @@ -635,6 +639,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ChartManagementService, AbuseUserReportEntityService, + AnnouncementEntityService, AntennaEntityService, AppEntityService, AuthSessionEntityService, @@ -678,7 +683,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ApRendererService, ApRequestService, ApResolverService, - LdSignatureService, + JsonLdService, RemoteLoggerService, RemoteUserResolveService, WebfingerService, @@ -770,6 +775,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting $ChartManagementService, $AbuseUserReportEntityService, + $AnnouncementEntityService, $AntennaEntityService, $AppEntityService, $AuthSessionEntityService, @@ -813,7 +819,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting $ApRendererService, $ApRequestService, $ApResolverService, - $LdSignatureService, + $JsonLdService, $RemoteLoggerService, $RemoteUserResolveService, $WebfingerService, diff --git a/packages/backend/src/core/CustomEmojiService.ts b/packages/backend/src/core/CustomEmojiService.ts index acc1c604e6..bfbc2b172d 100644 --- a/packages/backend/src/core/CustomEmojiService.ts +++ b/packages/backend/src/core/CustomEmojiService.ts @@ -22,7 +22,7 @@ import { ModerationLogService } from '@/core/ModerationLogService.js'; import type { Config } from '@/config.js'; import { DriveService } from './DriveService.js'; -const parseEmojiStrRegexp = /^(\w+)(?:@([\w.-]+))?$/; +const parseEmojiStrRegexp = /^([-\w]+)(?:@([\w.-]+))?$/; @Injectable() export class CustomEmojiService implements OnApplicationShutdown { @@ -369,10 +369,11 @@ export class CustomEmojiService implements OnApplicationShutdown { @bindThis public async populateEmojis(emojiNames: string[], noteUserHost: string | null): Promise> { const emojis = await Promise.all(emojiNames.map(x => this.populateEmoji(x, noteUserHost))); - const res = {} as any; + const res = {} as Record; for (let i = 0; i < emojiNames.length; i++) { - if (emojis[i] != null) { - res[emojiNames[i]] = emojis[i]; + const resolvedEmoji = emojis[i]; + if (resolvedEmoji != null) { + res[emojiNames[i]] = resolvedEmoji; } } return res; diff --git a/packages/backend/src/core/DriveService.ts b/packages/backend/src/core/DriveService.ts index 4203b03c74..af5451bfc8 100644 --- a/packages/backend/src/core/DriveService.ts +++ b/packages/backend/src/core/DriveService.ts @@ -477,14 +477,20 @@ export class DriveService { if (user && !force) { // Check if there is a file with the same hash - const much = await this.driveFilesRepository.findOneBy({ + const matched = await this.driveFilesRepository.findOneBy({ md5: info.md5, userId: user.id, }); - if (much) { - this.registerLogger.info(`file with same hash is found: ${much.id}`); - return much; + if (matched) { + this.registerLogger.info(`file with same hash is found: ${matched.id}`); + if (sensitive && !matched.isSensitive) { + // The file is federated as sensitive for this time, but was federated as non-sensitive before. + // Therefore, update the file to sensitive. + await this.driveFilesRepository.update({ id: matched.id }, { isSensitive: true }); + matched.isSensitive = true; + } + return matched; } } @@ -632,8 +638,8 @@ export class DriveService { @bindThis public async updateFile(file: MiDriveFile, values: Partial, updater: MiUser) { - const profile = await this.userProfilesRepository.findOneBy({ userId: file.userId }); - const alwaysMarkNsfw = (await this.roleService.getUserPolicies(file.userId)).alwaysMarkNsfw || (profile !== null && profile!.alwaysMarkNsfw); + const profile = file.userId ? await this.userProfilesRepository.findOneBy({ userId: file.userId }) : null; + const alwaysMarkNsfw = file.userId ? (await this.roleService.getUserPolicies(file.userId)).alwaysMarkNsfw || (profile !== null && profile!.alwaysMarkNsfw) : false; if (values.name != null && !this.driveFileEntityService.validateFileName(values.name)) { throw new DriveService.InvalidFileNameError(); diff --git a/packages/backend/src/core/FanoutTimelineEndpointService.ts b/packages/backend/src/core/FanoutTimelineEndpointService.ts index 6aa63d7d55..5725c795ed 100644 --- a/packages/backend/src/core/FanoutTimelineEndpointService.ts +++ b/packages/backend/src/core/FanoutTimelineEndpointService.ts @@ -13,7 +13,7 @@ import type { NotesRepository } from '@/models/_.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { FanoutTimelineName, FanoutTimelineService } from '@/core/FanoutTimelineService.js'; import { isUserRelated } from '@/misc/is-user-related.js'; -import { isPureRenote } from '@/misc/is-pure-renote.js'; +import { isQuote, isRenote } from '@/misc/is-renote.js'; import { CacheService } from '@/core/CacheService.js'; import { isReply } from '@/misc/is-reply.js'; import { isInstanceMuted } from '@/misc/is-instance-muted.js'; @@ -62,8 +62,8 @@ export class FanoutTimelineEndpointService { // 呼び出し元と以下の処理をシンプルにするためにdbFallbackを置き換える if (!ps.useDbFallback) ps.dbFallback = () => Promise.resolve([]); - const shouldPrepend = ps.sinceId && !ps.untilId; - const idCompare: (a: string, b: string) => number = shouldPrepend ? (a, b) => a < b ? -1 : 1 : (a, b) => a > b ? -1 : 1; + const ascending = ps.sinceId && !ps.untilId; + const idCompare: (a: string, b: string) => number = ascending ? (a, b) => a < b ? -1 : 1 : (a, b) => a > b ? -1 : 1; const redisResult = await this.fanoutTimelineService.getMulti(ps.redisTimelines, ps.untilId, ps.sinceId); @@ -101,7 +101,7 @@ export class FanoutTimelineEndpointService { if (ps.excludePureRenotes) { const parentFilter = filter; - filter = (note) => !isPureRenote(note) && parentFilter(note); + filter = (note) => (!isRenote(note) || isQuote(note)) && parentFilter(note); } if (ps.me) { @@ -122,9 +122,7 @@ export class FanoutTimelineEndpointService { filter = (note) => { if (isUserRelated(note, userIdsWhoBlockingMe, ps.ignoreAuthorFromBlock)) return false; if (isUserRelated(note, userIdsWhoMeMuting, ps.ignoreAuthorFromMute)) return false; - if (note.mentions.some(mention => userIdsWhoMeMuting.has(mention))) return false; - if (isPureRenote(note) && note.renote && note.renote.mentions.some(mention => userIdsWhoMeMuting.has(mention))) return false; - if (isPureRenote(note) && isUserRelated(note, userIdsWhoMeMutingRenotes, ps.ignoreAuthorFromMute)) return false; + if (!ps.ignoreAuthorFromMute && isRenote(note) && !isQuote(note) && userIdsWhoMeMutingRenotes.has(note.userId)) return false; if (isInstanceMuted(note, userMutedInstances)) return false; return parentFilter(note); @@ -150,9 +148,7 @@ export class FanoutTimelineEndpointService { if (ps.allowPartial ? redisTimeline.length !== 0 : redisTimeline.length >= ps.limit) { // 十分Redisからとれた - const result = redisTimeline.slice(0, ps.limit); - if (shouldPrepend) result.reverse(); - return result; + return redisTimeline.slice(0, ps.limit); } } @@ -160,8 +156,7 @@ export class FanoutTimelineEndpointService { const remainingToRead = ps.limit - redisTimeline.length; let dbUntil: string | null; let dbSince: string | null; - if (shouldPrepend) { - redisTimeline.reverse(); + if (ascending) { dbUntil = ps.untilId; dbSince = noteIds[noteIds.length - 1]; } else { @@ -169,7 +164,7 @@ export class FanoutTimelineEndpointService { dbSince = ps.sinceId; } const gotFromDb = await ps.dbFallback(dbUntil, dbSince, remainingToRead); - return shouldPrepend ? [...gotFromDb, ...redisTimeline] : [...redisTimeline, ...gotFromDb]; + return [...redisTimeline, ...gotFromDb]; } return await ps.dbFallback(ps.untilId, ps.sinceId, ps.limit); diff --git a/packages/backend/src/core/FetchInstanceMetadataService.ts b/packages/backend/src/core/FetchInstanceMetadataService.ts index bc270bd28f..aa16468ecb 100644 --- a/packages/backend/src/core/FetchInstanceMetadataService.ts +++ b/packages/backend/src/core/FetchInstanceMetadataService.ts @@ -51,21 +51,35 @@ export class FetchInstanceMetadataService { } @bindThis - public async tryLock(host: string): Promise { - const mutex = await this.redisClient.set(`fetchInstanceMetadata:mutex:${host}`, '1', 'GET'); - return mutex !== '1'; + // public for test + public async tryLock(host: string): Promise { + // TODO: マイグレーションなのであとで消す (2024.3.1) + this.redisClient.del(`fetchInstanceMetadata:mutex:${host}`); + + return await this.redisClient.set( + `fetchInstanceMetadata:mutex:v2:${host}`, '1', + 'EX', 30, // 30秒したら自動でロック解除 https://github.com/misskey-dev/misskey/issues/13506#issuecomment-1975375395 + 'GET' // 古い値を返す(なかったらnull) + ); } @bindThis - public unlock(host: string): Promise<'OK'> { - return this.redisClient.set(`fetchInstanceMetadata:mutex:${host}`, '0'); + // public for test + public unlock(host: string): Promise { + return this.redisClient.del(`fetchInstanceMetadata:mutex:v2:${host}`); } @bindThis public async fetchInstanceMetadata(instance: MiInstance, force = false): Promise { const host = instance.host; - // Acquire mutex to ensure no parallel runs - if (!await this.tryLock(host)) return; + + // finallyでunlockされてしまうのでtry内でロックチェックをしない + // (returnであってもfinallyは実行される) + if (!force && await this.tryLock(host) === '1') { + // 1が返ってきていたらロックされているという意味なので、何もしない + return; + } + try { if (!force) { const _instance = await this.federatedInstanceService.fetch(host); @@ -140,7 +154,7 @@ export class FetchInstanceMetadataService { throw new Error('No wellknown links'); } - const links = wellknown.links as any[]; + const links = wellknown.links as ({ rel: string, href: string; })[]; const link1_0 = links.find(link => link.rel === 'http://nodeinfo.diaspora.software/ns/schema/1.0'); const link2_0 = links.find(link => link.rel === 'http://nodeinfo.diaspora.software/ns/schema/2.0'); diff --git a/packages/backend/src/core/FileInfoService.ts b/packages/backend/src/core/FileInfoService.ts index 2d3312f247..9a9eae3cae 100644 --- a/packages/backend/src/core/FileInfoService.ts +++ b/packages/backend/src/core/FileInfoService.ts @@ -8,11 +8,13 @@ import * as crypto from 'node:crypto'; import * as stream from 'node:stream/promises'; import { Injectable } from '@nestjs/common'; import * as fileType from 'file-type'; +import FFmpeg from 'fluent-ffmpeg'; import isSvg from 'is-svg'; import probeImageSize from 'probe-image-size'; -import sharp from 'sharp'; import { sharpBmp } from '@misskey-dev/sharp-read-bmp'; import { encode } from 'blurhash'; +import { LoggerService } from '@/core/LoggerService.js'; +import type Logger from '@/logger.js'; import { bindThis } from '@/decorators.js'; export type FileInfo = { @@ -43,8 +45,12 @@ const TYPE_SVG = { @Injectable() export class FileInfoService { + private logger: Logger; + constructor( + private loggerService: LoggerService, ) { + this.logger = this.loggerService.getLogger('file-info'); } /** @@ -147,6 +153,34 @@ export class FileInfoService { return mime; } + /** + * ビデオファイルにビデオトラックがあるかどうかチェック + * (ない場合:m4a, webmなど) + * + * @param path ファイルパス + * @returns ビデオトラックがあるかどうか(エラー発生時は常に`true`を返す) + */ + @bindThis + private hasVideoTrackOnVideoFile(path: string): Promise { + const sublogger = this.logger.createSubLogger('ffprobe'); + sublogger.info(`Checking the video file. File path: ${path}`); + return new Promise((resolve) => { + try { + FFmpeg.ffprobe(path, (err, metadata) => { + if (err) { + sublogger.warn(`Could not check the video file. Returns true. File path: ${path}`, err); + resolve(true); + return; + } + resolve(metadata.streams.some((stream) => stream.codec_type === 'video')); + }); + } catch (err) { + sublogger.warn(`Could not check the video file. Returns true. File path: ${path}`, err as Error); + resolve(true); + } + }); + } + /** * Detect MIME Type and extension */ @@ -169,6 +203,20 @@ export class FileInfoService { return TYPE_SVG; } + if ((type.mime.startsWith('video') || type.mime === 'application/ogg') && !(await this.hasVideoTrackOnVideoFile(path))) { + const newMime = `audio/${type.mime.split('/')[1]}`; + if (newMime === 'audio/mp4') { + return { + mime: 'audio/mp4', + ext: 'm4a', + }; + } + return { + mime: newMime, + ext: type.ext, + }; + } + return { mime: this.fixMime(type.mime), ext: type.ext, diff --git a/packages/backend/src/core/MfmService.ts b/packages/backend/src/core/MfmService.ts index 9b99e8ccfe..625df1feaa 100644 --- a/packages/backend/src/core/MfmService.ts +++ b/packages/backend/src/core/MfmService.ts @@ -6,10 +6,11 @@ import { URL } from 'node:url'; import { Inject, Injectable } from '@nestjs/common'; import * as parse5 from 'parse5'; -import { Window } from 'happy-dom'; +import { Window, XMLSerializer } from 'happy-dom'; import { DI } from '@/di-symbols.js'; import type { Config } from '@/config.js'; import { intersperse } from '@/misc/prelude/array.js'; +import { normalizeForSearch } from '@/misc/normalize-for-search.js'; import type { IMentionedRemoteUsers } from '@/models/Note.js'; import { bindThis } from '@/decorators.js'; import * as TreeAdapter from '../../node_modules/parse5/dist/tree-adapters/default.js'; @@ -33,6 +34,8 @@ export class MfmService { // some AP servers like Pixelfed use br tags as well as newlines html = html.replace(/\r?\n/gi, '\n'); + const normalizedHashtagNames = hashtagNames == null ? undefined : new Set(hashtagNames.map(x => normalizeForSearch(x))); + const dom = parse5.parseFragment(html); let text = ''; @@ -85,7 +88,7 @@ export class MfmService { const href = node.attrs.find(x => x.name === 'href'); // ハッシュタグ - if (hashtagNames && href && hashtagNames.map(x => x.toLowerCase()).includes(txt.toLowerCase())) { + if (normalizedHashtagNames && href && normalizedHashtagNames.has(normalizeForSearch(txt))) { text += txt; // メンション } else if (txt.startsWith('@') && !(rel && rel.value.startsWith('me '))) { @@ -251,6 +254,8 @@ export class MfmService { const doc = window.document; + const body = doc.createElement('p'); + function appendChildren(children: mfm.MfmNode[], targetElement: any): void { if (children) { for (const child of children.map(x => (handlers as any)[x.type](x))) targetElement.appendChild(child); @@ -461,9 +466,9 @@ export class MfmService { }, }; - appendChildren(nodes, doc.body); + appendChildren(nodes, body); - return `

${doc.body.innerHTML}

`; + return new XMLSerializer().serializeToString(body); } // the toMastoApiHtml function was taken from Iceshrimp and written by zotan and modified by marie to work with the current MK version @@ -485,176 +490,176 @@ export class MfmService { } const handlers: { - [K in mfm.MfmNode['type']]: (node: mfm.NodeType) => any; - } = { - async bold(node) { - const el = doc.createElement('span'); - el.textContent = '**'; - await appendChildren(node.children, el); - el.textContent += '**'; - return el; - }, + [K in mfm.MfmNode['type']]: (node: mfm.NodeType) => any; + } = { + async bold(node) { + const el = doc.createElement('span'); + el.textContent = '**'; + await appendChildren(node.children, el); + el.textContent += '**'; + return el; + }, - async small(node) { - const el = doc.createElement('small'); - await appendChildren(node.children, el); - return el; - }, + async small(node) { + const el = doc.createElement('small'); + await appendChildren(node.children, el); + return el; + }, - async strike(node) { - const el = doc.createElement('span'); - el.textContent = '~~'; - await appendChildren(node.children, el); - el.textContent += '~~'; - return el; - }, + async strike(node) { + const el = doc.createElement('span'); + el.textContent = '~~'; + await appendChildren(node.children, el); + el.textContent += '~~'; + return el; + }, - async italic(node) { - const el = doc.createElement('span'); - el.textContent = '*'; - await appendChildren(node.children, el); - el.textContent += '*'; - return el; - }, + async italic(node) { + const el = doc.createElement('span'); + el.textContent = '*'; + await appendChildren(node.children, el); + el.textContent += '*'; + return el; + }, - async fn(node) { - const el = doc.createElement('span'); - el.textContent = '*'; - await appendChildren(node.children, el); - el.textContent += '*'; - return el; - }, + async fn(node) { + const el = doc.createElement('span'); + el.textContent = '*'; + await appendChildren(node.children, el); + el.textContent += '*'; + return el; + }, - blockCode(node) { - const pre = doc.createElement('pre'); - const inner = doc.createElement('code'); + blockCode(node) { + const pre = doc.createElement('pre'); + const inner = doc.createElement('code'); - const nodes = node.props.code - .split(/\r\n|\r|\n/) - .map((x) => doc.createTextNode(x)); + const nodes = node.props.code + .split(/\r\n|\r|\n/) + .map((x) => doc.createTextNode(x)); - for (const x of intersperse('br', nodes)) { - inner.appendChild(x === 'br' ? doc.createElement('br') : x); - } + for (const x of intersperse('br', nodes)) { + inner.appendChild(x === 'br' ? doc.createElement('br') : x); + } - pre.appendChild(inner); - return pre; - }, + pre.appendChild(inner); + return pre; + }, - async center(node) { - const el = doc.createElement('div'); - await appendChildren(node.children, el); - return el; - }, + async center(node) { + const el = doc.createElement('div'); + await appendChildren(node.children, el); + return el; + }, - emojiCode(node) { - return doc.createTextNode(`\u200B:${node.props.name}:\u200B`); - }, + emojiCode(node) { + return doc.createTextNode(`\u200B:${node.props.name}:\u200B`); + }, - unicodeEmoji(node) { - return doc.createTextNode(node.props.emoji); - }, + unicodeEmoji(node) { + return doc.createTextNode(node.props.emoji); + }, - hashtag: (node) => { - const a = doc.createElement('a'); - a.setAttribute('href', `${this.config.url}/tags/${node.props.hashtag}`); - a.textContent = `#${node.props.hashtag}`; - a.setAttribute('rel', 'tag'); - a.setAttribute('class', 'hashtag'); - return a; - }, + hashtag: (node) => { + const a = doc.createElement('a'); + a.setAttribute('href', `${this.config.url}/tags/${node.props.hashtag}`); + a.textContent = `#${node.props.hashtag}`; + a.setAttribute('rel', 'tag'); + a.setAttribute('class', 'hashtag'); + return a; + }, - inlineCode(node) { - const el = doc.createElement('code'); - el.textContent = node.props.code; - return el; - }, + inlineCode(node) { + const el = doc.createElement('code'); + el.textContent = node.props.code; + return el; + }, - mathInline(node) { - const el = doc.createElement('code'); - el.textContent = node.props.formula; - return el; - }, + mathInline(node) { + const el = doc.createElement('code'); + el.textContent = node.props.formula; + return el; + }, - mathBlock(node) { - const el = doc.createElement('code'); - el.textContent = node.props.formula; - return el; - }, + mathBlock(node) { + const el = doc.createElement('code'); + el.textContent = node.props.formula; + return el; + }, - async link(node) { - const a = doc.createElement('a'); - a.setAttribute('rel', 'nofollow noopener noreferrer'); - a.setAttribute('target', '_blank'); - a.setAttribute('href', node.props.url); - await appendChildren(node.children, a); - return a; - }, + async link(node) { + const a = doc.createElement('a'); + a.setAttribute('rel', 'nofollow noopener noreferrer'); + a.setAttribute('target', '_blank'); + a.setAttribute('href', node.props.url); + await appendChildren(node.children, a); + return a; + }, - async mention(node) { - const { username, host, acct } = node.props; - const resolved = mentionedRemoteUsers.find(remoteUser => remoteUser.username === username && remoteUser.host === host); + async mention(node) { + const { username, host, acct } = node.props; + const resolved = mentionedRemoteUsers.find(remoteUser => remoteUser.username === username && remoteUser.host === host); - const el = doc.createElement('span'); - if (!resolved) { - el.textContent = acct; - } else { - el.setAttribute('class', 'h-card'); - el.setAttribute('translate', 'no'); - const a = doc.createElement('a'); - a.setAttribute('href', resolved.url ? resolved.url : resolved.uri); - a.className = 'u-url mention'; - const span = doc.createElement('span'); - span.textContent = resolved.username || username; - a.textContent = '@'; - a.appendChild(span); - el.appendChild(a); - } + const el = doc.createElement('span'); + if (!resolved) { + el.textContent = acct; + } else { + el.setAttribute('class', 'h-card'); + el.setAttribute('translate', 'no'); + const a = doc.createElement('a'); + a.setAttribute('href', resolved.url ? resolved.url : resolved.uri); + a.className = 'u-url mention'; + const span = doc.createElement('span'); + span.textContent = resolved.username || username; + a.textContent = '@'; + a.appendChild(span); + el.appendChild(a); + } - return el; - }, + return el; + }, - async quote(node) { - const el = doc.createElement('blockquote'); - await appendChildren(node.children, el); - return el; - }, + async quote(node) { + const el = doc.createElement('blockquote'); + await appendChildren(node.children, el); + return el; + }, - text(node) { - const el = doc.createElement('span'); - const nodes = node.props.text - .split(/\r\n|\r|\n/) - .map((x) => doc.createTextNode(x)); + text(node) { + const el = doc.createElement('span'); + const nodes = node.props.text + .split(/\r\n|\r|\n/) + .map((x) => doc.createTextNode(x)); - for (const x of intersperse('br', nodes)) { - el.appendChild(x === 'br' ? doc.createElement('br') : x); - } + for (const x of intersperse('br', nodes)) { + el.appendChild(x === 'br' ? doc.createElement('br') : x); + } - return el; - }, + return el; + }, - url(node) { - const a = doc.createElement('a'); - a.setAttribute('rel', 'nofollow noopener noreferrer'); - a.setAttribute('target', '_blank'); - a.setAttribute('href', node.props.url); - a.textContent = node.props.url.replace(/^https?:\/\//, ''); - return a; - }, + url(node) { + const a = doc.createElement('a'); + a.setAttribute('rel', 'nofollow noopener noreferrer'); + a.setAttribute('target', '_blank'); + a.setAttribute('href', node.props.url); + a.textContent = node.props.url.replace(/^https?:\/\//, ''); + return a; + }, - search: (node) => { - const a = doc.createElement('a'); - a.setAttribute('href', `https://www.google.com/search?q=${node.props.query}`); - a.textContent = node.props.content; - return a; - }, + search: (node) => { + const a = doc.createElement('a'); + a.setAttribute('href', `https://www.google.com/search?q=${node.props.query}`); + a.textContent = node.props.content; + return a; + }, - async plain(node) { - const el = doc.createElement('span'); - await appendChildren(node.children, el); - return el; - }, - }; + async plain(node) { + const el = doc.createElement('span'); + await appendChildren(node.children, el); + return el; + }, + }; await appendChildren(nodes, doc.body); diff --git a/packages/backend/src/core/NoteCreateService.ts b/packages/backend/src/core/NoteCreateService.ts index d51315f71f..41efa76f3f 100644 --- a/packages/backend/src/core/NoteCreateService.ts +++ b/packages/backend/src/core/NoteCreateService.ts @@ -282,7 +282,7 @@ export class NoteCreateService implements OnApplicationShutdown { data.visibility = 'home'; } - if (data.renote) { + if (this.isRenote(data)) { switch (data.renote.visibility) { case 'public': // public noteは無条件にrenote可能 @@ -309,7 +309,7 @@ export class NoteCreateService implements OnApplicationShutdown { } // Check blocking - if (data.renote && !this.isQuote(data)) { + if (this.isRenote(data) && !this.isQuote(data)) { if (data.renote.userHost === null) { if (data.renote.userId !== user.id) { const blocked = await this.userBlockingService.checkBlocked(data.renote.userId, user.id); @@ -495,7 +495,7 @@ export class NoteCreateService implements OnApplicationShutdown { } // Check blocking - if (data.renote && !this.isQuote(data)) { + if (this.isRenote(data) && !this.isQuote(data)) { if (data.renote.userHost === null) { if (data.renote.userId !== user.id) { const blocked = await this.userBlockingService.checkBlocked(data.renote.userId, user.id); @@ -670,6 +670,7 @@ export class NoteCreateService implements OnApplicationShutdown { noteVisibility: insert.visibility, userId: user.id, userHost: user.host, + channelId: insert.channelId, }); await transactionalEntityManager.insert(MiPoll, poll); @@ -863,7 +864,7 @@ export class NoteCreateService implements OnApplicationShutdown { } // If it is renote - if (data.renote) { + if (this.isRenote(data)) { const type = this.isQuote(data) ? 'quote' : 'renote'; // Notify @@ -1063,9 +1064,20 @@ export class NoteCreateService implements OnApplicationShutdown { } @bindThis - private isQuote(note: Option): note is Option & { renote: MiNote } { - // sync with misc/is-quote.ts - return !!note.renote && (!!note.text || !!note.cw || (!!note.files && !!note.files.length) || !!note.poll); + private isRenote(note: Option): note is Option & { renote: MiNote } { + return note.renote != null; + } + + @bindThis + private isQuote(note: Option & { renote: MiNote }): note is Option & { renote: MiNote } & ( + { text: string } | { cw: string } | { reply: MiNote } | { poll: IPoll } | { files: MiDriveFile[] } + ) { + // NOTE: SYNC WITH misc/is-quote.ts + return note.text != null || + note.reply != null || + note.cw != null || + note.poll != null || + (note.files != null && note.files.length > 0); } @bindThis @@ -1141,7 +1153,7 @@ export class NoteCreateService implements OnApplicationShutdown { private async renderNoteOrRenoteActivity(data: Option, note: MiNote) { if (data.localOnly) return null; - const content = data.renote && !this.isQuote(data) + const content = this.isRenote(data) && !this.isQuote(data) ? this.apRendererService.renderAnnounce(data.renote.uri ? data.renote.uri : `${this.config.url}/notes/${data.renote.id}`, note) : this.apRendererService.renderCreate(await this.apRendererService.renderNote(note, false), note); diff --git a/packages/backend/src/core/NoteDeleteService.ts b/packages/backend/src/core/NoteDeleteService.ts index 471ade92c7..af65750a01 100644 --- a/packages/backend/src/core/NoteDeleteService.ts +++ b/packages/backend/src/core/NoteDeleteService.ts @@ -24,7 +24,7 @@ import { bindThis } from '@/decorators.js'; import { MetaService } from '@/core/MetaService.js'; import { SearchService } from '@/core/SearchService.js'; import { ModerationLogService } from '@/core/ModerationLogService.js'; -import { isPureRenote } from '@/misc/is-pure-renote.js'; +import { isQuote, isRenote } from '@/misc/is-renote.js'; @Injectable() export class NoteDeleteService { @@ -86,7 +86,7 @@ export class NoteDeleteService { let renote: MiNote | null = null; // if deleted note is renote - if (isPureRenote(note)) { + if (isRenote(note) && !isQuote(note)) { renote = await this.notesRepository.findOneBy({ id: note.renoteId, }); diff --git a/packages/backend/src/core/NoteEditService.ts b/packages/backend/src/core/NoteEditService.ts index 6949136e69..0cb58d04a2 100644 --- a/packages/backend/src/core/NoteEditService.ts +++ b/packages/backend/src/core/NoteEditService.ts @@ -298,7 +298,7 @@ export class NoteEditService implements OnApplicationShutdown { data.visibility = 'home'; } - if (data.renote) { + if (this.isRenote(data)) { if (data.renote.id === oldnote.id) { throw new Error("A note can't renote itself"); } @@ -329,7 +329,7 @@ export class NoteEditService implements OnApplicationShutdown { } // Check blocking - if (data.renote && !this.isQuote(data)) { + if (this.isRenote(data) && !this.isQuote(data)) { if (data.renote.userHost === null) { if (data.renote.userId !== user.id) { const blocked = await this.userBlockingService.checkBlocked(data.renote.userId, user.id); @@ -346,7 +346,7 @@ export class NoteEditService implements OnApplicationShutdown { } // ローカルのみをRenoteしたらローカルのみにする - if (data.renote && data.renote.localOnly && data.channel == null) { + if (this.isRenote(data) && data.renote.localOnly && data.channel == null) { data.localOnly = true; } @@ -528,6 +528,7 @@ export class NoteEditService implements OnApplicationShutdown { noteVisibility: note.visibility, userId: user.id, userHost: user.host, + channelId: data.channel ? data.channel.id : null, }); if (!oldnote.hasPoll) { @@ -693,7 +694,7 @@ export class NoteEditService implements OnApplicationShutdown { } // 投稿がRenoteかつ投稿者がローカルユーザーかつRenote元の投稿の投稿者がリモートユーザーなら配送 - if (data.renote && data.renote.userHost !== null) { + if (this.isRenote(data) && data.renote.userHost !== null) { const u = await this.usersRepository.findOneBy({ id: data.renote.userId }); if (u && this.userEntityService.isRemoteUser(u)) dm.addDirectRecipe(u); } @@ -754,9 +755,20 @@ export class NoteEditService implements OnApplicationShutdown { } @bindThis - private isQuote(note: Option): note is Option & { renote: MiNote } { - // sync with misc/is-quote.ts - return !!note.renote && (!!note.text || !!note.cw || (!!note.files && !!note.files.length) || !!note.poll); + private isRenote(note: Option): note is Option & { renote: MiNote } { + return note.renote != null; + } + + @bindThis + private isQuote(note: Option & { renote: MiNote }): note is Option & { renote: MiNote } & ( + { text: string } | { cw: string } | { reply: MiNote } | { poll: IPoll } | { files: MiDriveFile[] } + ) { + // NOTE: SYNC WITH misc/is-quote.ts + return note.text != null || + note.reply != null || + note.cw != null || + note.poll != null || + (note.files != null && note.files.length > 0); } @bindThis @@ -805,7 +817,7 @@ export class NoteEditService implements OnApplicationShutdown { const user = await this.usersRepository.findOneBy({ id: note.userId }); if (user == null) throw new Error('user not found'); - const content = data.renote && !this.isQuote(data) + const content = this.isRenote(data) && !this.isQuote(data) ? this.apRendererService.renderAnnounce(data.renote.uri ? data.renote.uri : `${this.config.url}/notes/${data.renote.id}`, note) : this.apRendererService.renderUpdate(await this.apRendererService.renderUpNote(note, false), user); diff --git a/packages/backend/src/core/PushNotificationService.ts b/packages/backend/src/core/PushNotificationService.ts index 3b706d9854..6a845b951d 100644 --- a/packages/backend/src/core/PushNotificationService.ts +++ b/packages/backend/src/core/PushNotificationService.ts @@ -101,7 +101,7 @@ export class PushNotificationService implements OnApplicationShutdown { type, body: (type === 'notification' || type === 'unreadAntennaNote') ? truncateBody(type, body) : body, userId, - dateTime: (new Date()).getTime(), + dateTime: Date.now(), }), { proxy: this.config.proxy, }).catch((err: any) => { diff --git a/packages/backend/src/core/RoleService.ts b/packages/backend/src/core/RoleService.ts index 2059a6e784..f5a753afc7 100644 --- a/packages/backend/src/core/RoleService.ts +++ b/packages/backend/src/core/RoleService.ts @@ -209,45 +209,79 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit { private evalCond(user: MiUser, roles: MiRole[], value: RoleCondFormulaValue): boolean { try { switch (value.type) { + // ~かつ~ case 'and': { return value.values.every(v => this.evalCond(user, roles, v)); } + // ~または~ case 'or': { return value.values.some(v => this.evalCond(user, roles, v)); } + // ~ではない case 'not': { return !this.evalCond(user, roles, value.value); } + // マニュアルロールがアサインされている case 'roleAssignedTo': { return roles.some(r => r.id === value.roleId); } + // ローカルユーザのみ case 'isLocal': { return this.userEntityService.isLocalUser(user); } + // リモートユーザのみ case 'isRemote': { return this.userEntityService.isRemoteUser(user); } + // サスペンド済みユーザである + case 'isSuspended': { + return user.isSuspended; + } + // 鍵アカウントユーザである + case 'isLocked': { + return user.isLocked; + } + // botユーザである + case 'isBot': { + return user.isBot; + } + // 猫である + case 'isCat': { + return user.isCat; + } + // 「ユーザを見つけやすくする」が有効なアカウント + case 'isExplorable': { + return user.isExplorable; + } + // ユーザが作成されてから指定期間経過した case 'createdLessThan': { return this.idService.parse(user.id).date.getTime() > (Date.now() - (value.sec * 1000)); } + // ユーザが作成されてから指定期間経っていない case 'createdMoreThan': { return this.idService.parse(user.id).date.getTime() < (Date.now() - (value.sec * 1000)); } + // フォロワー数が指定値以下 case 'followersLessThanOrEq': { return user.followersCount <= value.value; } + // フォロワー数が指定値以上 case 'followersMoreThanOrEq': { return user.followersCount >= value.value; } + // フォロー数が指定値以下 case 'followingLessThanOrEq': { return user.followingCount <= value.value; } + // フォロー数が指定値以上 case 'followingMoreThanOrEq': { return user.followingCount >= value.value; } + // ノート数が指定値以下 case 'notesLessThanOrEq': { return user.notesCount <= value.value; } + // ノート数が指定値以上 case 'notesMoreThanOrEq': { return user.notesCount >= value.value; } diff --git a/packages/backend/src/core/WebAuthnService.ts b/packages/backend/src/core/WebAuthnService.ts index 42fbed2110..ec9f4484a4 100644 --- a/packages/backend/src/core/WebAuthnService.ts +++ b/packages/backend/src/core/WebAuthnService.ts @@ -10,7 +10,7 @@ import { generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, } from '@simplewebauthn/server'; -import { AttestationFormat, isoCBOR } from '@simplewebauthn/server/helpers'; +import { AttestationFormat, isoCBOR, isoUint8Array } from '@simplewebauthn/server/helpers'; import { DI } from '@/di-symbols.js'; import type { UserSecurityKeysRepository } from '@/models/_.js'; import type { Config } from '@/config.js'; @@ -49,7 +49,7 @@ export class WebAuthnService { const instance = await this.metaService.fetch(); return { origin: this.config.url, - rpId: this.config.host, + rpId: this.config.hostname, rpName: instance.name ?? this.config.host, rpIcon: instance.iconUrl ?? undefined, }; @@ -65,13 +65,12 @@ export class WebAuthnService { const registrationOptions = await generateRegistrationOptions({ rpName: relyingParty.rpName, rpID: relyingParty.rpId, - userID: userId, + userID: isoUint8Array.fromUTF8String(userId), userName: userName, userDisplayName: userDisplayName, attestationType: 'indirect', - excludeCredentials: keys.map(key => ({ - id: Buffer.from(key.id, 'base64url'), - type: 'public-key', + excludeCredentials: keys.map(key => (<{ id: string; transports?: AuthenticatorTransportFuture[]; }>{ + id: key.id, transports: key.transports ?? undefined, })), authenticatorSelection: { @@ -87,7 +86,7 @@ export class WebAuthnService { @bindThis public async verifyRegistration(userId: MiUser['id'], response: RegistrationResponseJSON): Promise<{ - credentialID: Uint8Array; + credentialID: string; credentialPublicKey: Uint8Array; attestationObject: Uint8Array; fmt: AttestationFormat; @@ -144,6 +143,7 @@ export class WebAuthnService { @bindThis public async initiateAuthentication(userId: MiUser['id']): Promise { + const relyingParty = await this.getRelyingParty(); const keys = await this.userSecurityKeysRepository.findBy({ userId: userId, }); @@ -153,9 +153,9 @@ export class WebAuthnService { } const authenticationOptions = await generateAuthenticationOptions({ - allowCredentials: keys.map(key => ({ - id: Buffer.from(key.id, 'base64url'), - type: 'public-key', + rpID: relyingParty.rpId, + allowCredentials: keys.map(key => (<{ id: string; transports?: AuthenticatorTransportFuture[]; }>{ + id: key.id, transports: key.transports ?? undefined, })), userVerification: 'preferred', @@ -219,7 +219,7 @@ export class WebAuthnService { expectedOrigin: relyingParty.origin, expectedRPID: relyingParty.rpId, authenticator: { - credentialID: Buffer.from(key.id, 'base64url'), + credentialID: key.id, credentialPublicKey: Buffer.from(key.publicKey, 'base64url'), counter: key.counter, transports: key.transports ? key.transports as AuthenticatorTransportFuture[] : undefined, diff --git a/packages/backend/src/core/activitypub/ApInboxService.ts b/packages/backend/src/core/activitypub/ApInboxService.ts index 6ff03b22e1..cf66816566 100644 --- a/packages/backend/src/core/activitypub/ApInboxService.ts +++ b/packages/backend/src/core/activitypub/ApInboxService.ts @@ -28,6 +28,7 @@ import type { UsersRepository, NotesRepository, FollowingsRepository, AbuseUserR import { bindThis } from '@/decorators.js'; import type { MiRemoteUser } from '@/models/User.js'; import { isNotNull } from '@/misc/is-not-null.js'; +import { GlobalEventService } from '@/core/GlobalEventService.js'; import { getApHrefNullable, getApId, getApIds, getApType, isAccept, isActor, isAdd, isAnnounce, isBlock, isCollection, isCollectionOrOrderedCollection, isCreate, isDelete, isFlag, isFollow, isLike, isMove, isPost, isReject, isRemove, isTombstone, isUndo, isUpdate, validActor, validPost } from './type.js'; import { ApNoteService } from './models/ApNoteService.js'; import { ApLoggerService } from './ApLoggerService.js'; @@ -36,9 +37,8 @@ import { ApResolverService } from './ApResolverService.js'; import { ApAudienceService } from './ApAudienceService.js'; import { ApPersonService } from './models/ApPersonService.js'; import { ApQuestionService } from './models/ApQuestionService.js'; -import { GlobalEventService } from '@/core/GlobalEventService.js'; import type { Resolver } from './ApResolverService.js'; -import type { IAccept, IAdd, IAnnounce, IBlock, ICreate, IDelete, IFlag, IFollow, ILike, IObject, IReject, IRemove, IUndo, IUpdate, IMove } from './type.js'; +import type { IAccept, IAdd, IAnnounce, IBlock, ICreate, IDelete, IFlag, IFollow, ILike, IObject, IReject, IRemove, IUndo, IUpdate, IMove, IPost } from './type.js'; @Injectable() export class ApInboxService { @@ -90,13 +90,15 @@ export class ApInboxService { } @bindThis - public async performActivity(actor: MiRemoteUser, activity: IObject): Promise { + public async performActivity(actor: MiRemoteUser, activity: IObject): Promise { + let result = undefined as string | void; if (isCollectionOrOrderedCollection(activity)) { + const results = [] as [string, string | void][]; const resolver = this.apResolverService.createResolver(); for (const item of toArray(isCollection(activity) ? activity.items : activity.orderedItems)) { const act = await resolver.resolve(item); try { - await this.performOneActivity(actor, act); + results.push([getApId(item), await this.performOneActivity(actor, act)]); } catch (err) { if (err instanceof Error || typeof err === 'string') { this.logger.error(err); @@ -105,8 +107,13 @@ export class ApInboxService { } } } + + const hasReason = results.some(([, reason]) => (reason != null && !reason.startsWith('ok'))); + if (hasReason) { + result = results.map(([id, reason]) => `${id}: ${reason}`).join('\n'); + } } else { - await this.performOneActivity(actor, activity); + result = await this.performOneActivity(actor, activity); } // ついでにリモートユーザーの情報が古かったら更新しておく @@ -117,42 +124,43 @@ export class ApInboxService { }); } } + return result; } @bindThis - public async performOneActivity(actor: MiRemoteUser, activity: IObject): Promise { + public async performOneActivity(actor: MiRemoteUser, activity: IObject): Promise { if (actor.isSuspended) return; if (isCreate(activity)) { - await this.create(actor, activity); + return await this.create(actor, activity); } else if (isDelete(activity)) { - await this.delete(actor, activity); + return await this.delete(actor, activity); } else if (isUpdate(activity)) { - await this.update(actor, activity); + return await this.update(actor, activity); } else if (isFollow(activity)) { - await this.follow(actor, activity); + return await this.follow(actor, activity); } else if (isAccept(activity)) { - await this.accept(actor, activity); + return await this.accept(actor, activity); } else if (isReject(activity)) { - await this.reject(actor, activity); + return await this.reject(actor, activity); } else if (isAdd(activity)) { - await this.add(actor, activity).catch(err => this.logger.error(err)); + return await this.add(actor, activity); } else if (isRemove(activity)) { - await this.remove(actor, activity).catch(err => this.logger.error(err)); + return await this.remove(actor, activity); } else if (isAnnounce(activity)) { - await this.announce(actor, activity); + return await this.announce(actor, activity); } else if (isLike(activity)) { - await this.like(actor, activity); + return await this.like(actor, activity); } else if (isUndo(activity)) { - await this.undo(actor, activity); + return await this.undo(actor, activity); } else if (isBlock(activity)) { - await this.block(actor, activity); + return await this.block(actor, activity); } else if (isFlag(activity)) { - await this.flag(actor, activity); + return await this.flag(actor, activity); } else if (isMove(activity)) { - await this.move(actor, activity); + return await this.move(actor, activity); } else { - this.logger.warn(`unrecognized activity type: ${activity.type}`); + return `unrecognized activity type: ${activity.type}`; } } @@ -234,38 +242,49 @@ export class ApInboxService { } @bindThis - private async add(actor: MiRemoteUser, activity: IAdd): Promise { + private async add(actor: MiRemoteUser, activity: IAdd): Promise { if (actor.uri !== activity.actor) { - throw new Error('invalid actor'); + return 'invalid actor'; } if (activity.target == null) { - throw new Error('target is null'); + return 'target is null'; } if (activity.target === actor.featured) { const note = await this.apNoteService.resolveNote(activity.object); - if (note == null) throw new Error('note not found'); + if (note == null) return 'note not found'; await this.notePiningService.addPinned(actor, note.id); return; } - throw new Error(`unknown target: ${activity.target}`); + return `unknown target: ${activity.target}`; } @bindThis - private async announce(actor: MiRemoteUser, activity: IAnnounce): Promise { + private async announce(actor: MiRemoteUser, activity: IAnnounce): Promise { const uri = getApId(activity); this.logger.info(`Announce: ${uri}`); - const targetUri = getApId(activity.object); + const resolver = this.apResolverService.createResolver(); - await this.announceNote(actor, activity, targetUri); + if (!activity.object) return 'skip: activity has no object property'; + const targetUri = getApId(activity.object); + if (targetUri.startsWith('bear:')) return 'skip: bearcaps url not supported.'; + + const target = await resolver.resolve(activity.object).catch(e => { + this.logger.error(`Resolution failed: ${e}`); + return e; + }); + + if (isPost(target)) return await this.announceNote(actor, activity, target); + + return `skip: unknown object type ${getApType(target)}`; } @bindThis - private async announceNote(actor: MiRemoteUser, activity: IAnnounce, targetUri: string): Promise { + private async announceNote(actor: MiRemoteUser, activity: IAnnounce, target: IPost): Promise { const uri = getApId(activity); if (actor.isSuspended) { @@ -288,24 +307,21 @@ export class ApInboxService { // Announce対象をresolve let renote; try { - renote = await this.apNoteService.resolveNote(targetUri); - if (renote == null) throw new Error('announce target is null'); + renote = await this.apNoteService.resolveNote(target); + if (renote == null) return 'announce target is null'; } catch (err) { // 対象が4xxならスキップ if (err instanceof StatusError) { if (!err.isRetryable) { - this.logger.warn(`Ignored announce target ${targetUri} - ${err.statusCode}`); - return; + return `Ignored announce target ${target.id} - ${err.statusCode}`; } - - this.logger.warn(`Error in announce target ${targetUri} - ${err.statusCode}`); + return `Error in announce target ${target.id} - ${err.statusCode}`; } throw err; } if (!await this.noteEntityService.isVisibleForMe(renote, actor.id)) { - this.logger.warn('skip: invalid actor for this activity'); - return; + return 'skip: invalid actor for this activity'; } this.logger.info(`Creating the (Re)Note: ${uri}`); @@ -314,8 +330,7 @@ export class ApInboxService { const createdAt = activity.published ? new Date(activity.published) : null; if (createdAt && createdAt < this.idService.parse(renote.id).date) { - this.logger.warn('skip: malformed createdAt'); - return; + return 'skip: malformed createdAt'; } await this.noteCreateService.create(actor, { @@ -349,11 +364,15 @@ export class ApInboxService { } @bindThis - private async create(actor: MiRemoteUser, activity: ICreate): Promise { + private async create(actor: MiRemoteUser, activity: ICreate): Promise { const uri = getApId(activity); this.logger.info(`Create: ${uri}`); + if (!activity.object) return 'skip: activity has no object property'; + const targetUri = getApId(activity.object); + if (targetUri.startsWith('bear:')) return 'skip: bearcaps url not supported.'; + // copy audiences between activity <=> object. if (typeof activity.object === 'object') { const to = unique(concat([toArray(activity.to), toArray(activity.object.to)])); @@ -380,7 +399,7 @@ export class ApInboxService { if (isPost(object)) { await this.createNote(resolver, actor, object, false, activity); } else { - this.logger.warn(`Unknown type: ${getApType(object)}`); + return `Unknown type: ${getApType(object)}`; } } @@ -422,7 +441,7 @@ export class ApInboxService { @bindThis private async delete(actor: MiRemoteUser, activity: IDelete): Promise { if (actor.uri !== activity.actor) { - throw new Error('invalid actor'); + return 'invalid actor'; } // 削除対象objectのtype @@ -581,29 +600,29 @@ export class ApInboxService { } @bindThis - private async remove(actor: MiRemoteUser, activity: IRemove): Promise { + private async remove(actor: MiRemoteUser, activity: IRemove): Promise { if (actor.uri !== activity.actor) { - throw new Error('invalid actor'); + return 'invalid actor'; } if (activity.target == null) { - throw new Error('target is null'); + return 'target is null'; } if (activity.target === actor.featured) { const note = await this.apNoteService.resolveNote(activity.object); - if (note == null) throw new Error('note not found'); + if (note == null) return 'note not found'; await this.notePiningService.removePinned(actor, note.id); return; } - throw new Error(`unknown target: ${activity.target}`); + return `unknown target: ${activity.target}`; } @bindThis private async undo(actor: MiRemoteUser, activity: IUndo): Promise { if (actor.uri !== activity.actor) { - throw new Error('invalid actor'); + return 'invalid actor'; } const uri = activity.id ?? activity; @@ -614,7 +633,7 @@ export class ApInboxService { const object = await resolver.resolve(activity.object).catch(e => { this.logger.error(`Resolution failed: ${e}`); - throw e; + return e; }); // don't queue because the sender may attempt again when timeout diff --git a/packages/backend/src/core/activitypub/ApRendererService.ts b/packages/backend/src/core/activitypub/ApRendererService.ts index 38175b2059..90784fdc1d 100644 --- a/packages/backend/src/core/activitypub/ApRendererService.ts +++ b/packages/backend/src/core/activitypub/ApRendererService.ts @@ -29,7 +29,7 @@ import { CustomEmojiService } from '@/core/CustomEmojiService.js'; import { isNotNull } from '@/misc/is-not-null.js'; import { IdService } from '@/core/IdService.js'; import { MetaService } from '../MetaService.js'; -import { LdSignatureService } from './LdSignatureService.js'; +import { JsonLdService } from './JsonLdService.js'; import { ApMfmService } from './ApMfmService.js'; import { CONTEXT } from './misc/contexts.js'; import type { IAccept, IActivity, IAdd, IAnnounce, IApDocument, IApEmoji, IApHashtag, IApImage, IApMention, IBlock, ICreate, IDelete, IFlag, IFollow, IKey, ILike, IMove, IObject, IPost, IQuestion, IReject, IRemove, ITombstone, IUndo, IUpdate } from './type.js'; @@ -61,7 +61,7 @@ export class ApRendererService { private customEmojiService: CustomEmojiService, private userEntityService: UserEntityService, private driveFileEntityService: DriveFileEntityService, - private ldSignatureService: LdSignatureService, + private jsonLdService: JsonLdService, private userKeypairService: UserKeypairService, private apMfmService: ApMfmService, private mfmService: MfmService, @@ -173,6 +173,7 @@ export class ApRendererService { url: this.driveFileEntityService.getPublicUrl(file), name: file.comment, summary: file.comment, + sensitive: file.isSensitive, }; } @@ -794,9 +795,9 @@ export class ApRendererService { public async attachLdSignature(activity: any, user: { id: MiUser['id']; host: null; }): Promise { const keypair = await this.userKeypairService.getUserKeypair(user.id); - const ldSignature = this.ldSignatureService.use(); - ldSignature.debug = false; - activity = await ldSignature.signRsaSignature2017(activity, keypair.privateKey, `${this.config.url}/users/${user.id}#main-key`); + const jsonLd = this.jsonLdService.use(); + jsonLd.debug = false; + activity = await jsonLd.signRsaSignature2017(activity, keypair.privateKey, `${this.config.url}/users/${user.id}#main-key`); return activity; } diff --git a/packages/backend/src/core/activitypub/LdSignatureService.ts b/packages/backend/src/core/activitypub/JsonLdService.ts similarity index 86% rename from packages/backend/src/core/activitypub/LdSignatureService.ts rename to packages/backend/src/core/activitypub/JsonLdService.ts index 2ec6dc4585..100d4fa19f 100644 --- a/packages/backend/src/core/activitypub/LdSignatureService.ts +++ b/packages/backend/src/core/activitypub/JsonLdService.ts @@ -7,14 +7,14 @@ import * as crypto from 'node:crypto'; import { Injectable } from '@nestjs/common'; import { HttpRequestService } from '@/core/HttpRequestService.js'; import { bindThis } from '@/decorators.js'; -import { CONTEXT, CONTEXTS } from './misc/contexts.js'; +import { CONTEXT, PRELOADED_CONTEXTS } from './misc/contexts.js'; import { validateContentTypeSetAsJsonLD } from './misc/validator.js'; import type { JsonLdDocument } from 'jsonld'; -import type { JsonLd, RemoteDocument } from 'jsonld/jsonld-spec.js'; +import type { JsonLd as JsonLdObject, RemoteDocument } from 'jsonld/jsonld-spec.js'; -// RsaSignature2017 based from https://github.com/transmute-industries/RsaSignature2017 +// RsaSignature2017 implementation is based on https://github.com/transmute-industries/RsaSignature2017 -class LdSignature { +class JsonLd { public debug = false; public preLoad = true; public loderTimeout = 5000; @@ -101,8 +101,6 @@ class LdSignature { @bindThis public async normalize(data: JsonLdDocument): Promise { const customLoader = this.getLoader(); - // XXX: Importing jsonld dynamically since Jest frequently fails to import it statically - // https://github.com/misskey-dev/misskey/pull/9894#discussion_r1103753595 return (await import('jsonld')).default.normalize(data, { documentLoader: customLoader, }); @@ -114,11 +112,11 @@ class LdSignature { if (!/^https?:\/\//.test(url)) throw new Error(`Invalid URL ${url}`); if (this.preLoad) { - if (url in CONTEXTS) { + if (url in PRELOADED_CONTEXTS) { if (this.debug) console.debug(`HIT: ${url}`); return { contextUrl: undefined, - document: CONTEXTS[url], + document: PRELOADED_CONTEXTS[url], documentUrl: url, }; } @@ -135,7 +133,7 @@ class LdSignature { } @bindThis - private async fetchDocument(url: string): Promise { + private async fetchDocument(url: string): Promise { const json = await this.httpRequestService.send( url, { @@ -156,7 +154,7 @@ class LdSignature { } }); - return json as JsonLd; + return json as JsonLdObject; } @bindThis @@ -168,14 +166,14 @@ class LdSignature { } @Injectable() -export class LdSignatureService { +export class JsonLdService { constructor( private httpRequestService: HttpRequestService, ) { } @bindThis - public use(): LdSignature { - return new LdSignature(this.httpRequestService); + public use(): JsonLd { + return new JsonLd(this.httpRequestService); } } diff --git a/packages/backend/src/core/activitypub/misc/contexts.ts b/packages/backend/src/core/activitypub/misc/contexts.ts index 4ff114bbf5..815b20b910 100644 --- a/packages/backend/src/core/activitypub/misc/contexts.ts +++ b/packages/backend/src/core/activitypub/misc/contexts.ts @@ -570,7 +570,7 @@ const extension_context_definition = { export const CONTEXT: (string | Context)[] = [...context_iris, extension_context_definition]; -export const CONTEXTS: Record = { +export const PRELOADED_CONTEXTS: Record = { 'https://w3id.org/identity/v1': id_v1, 'https://w3id.org/security/v1': security_v1, 'https://www.w3.org/ns/activitystreams': activitystreams, diff --git a/packages/backend/src/core/activitypub/models/ApImageService.ts b/packages/backend/src/core/activitypub/models/ApImageService.ts index 1017a5018a..3d98c5b764 100644 --- a/packages/backend/src/core/activitypub/models/ApImageService.ts +++ b/packages/backend/src/core/activitypub/models/ApImageService.ts @@ -18,7 +18,7 @@ import { checkHttps } from '@/misc/check-https.js'; import { FederatedInstanceService } from '@/core/FederatedInstanceService.js'; import { ApResolverService } from '../ApResolverService.js'; import { ApLoggerService } from '../ApLoggerService.js'; -import type { IObject } from '../type.js'; +import { isDocument, type IObject } from '../type.js'; @Injectable() export class ApImageService { @@ -41,7 +41,7 @@ export class ApImageService { * Imageを作成します。 */ @bindThis - public async createImage(actor: MiRemoteUser, value: string | IObject): Promise { + public async createImage(actor: MiRemoteUser, value: string | IObject): Promise { // 投稿者が凍結されていたらスキップ if (actor.isSuspended) { throw new Error('actor has been suspended'); @@ -49,16 +49,18 @@ export class ApImageService { const image = await this.apResolverService.createResolver().resolve(value); + if (!isDocument(image)) return null; + if (image.url == null) { - throw new Error('invalid image: url not provided'); + return null; } if (typeof image.url !== 'string') { - throw new Error('invalid image: unexpected type of url: ' + JSON.stringify(image.url, null, 2)); + return null; } if (!checkHttps(image.url)) { - throw new Error('invalid image: unexpected schema of url: ' + image.url); + return null; } this.logger.info(`Creating the Image: ${image.url}`); @@ -94,12 +96,11 @@ export class ApImageService { /** * Imageを解決します。 * - * Misskeyに対象のImageが登録されていればそれを返し、そうでなければ - * リモートサーバーからフェッチしてMisskeyに登録しそれを返します。 + * ImageをリモートサーバーからフェッチしてMisskeyに登録しそれを返します。 */ @bindThis - public async resolveImage(actor: MiRemoteUser, value: string | IObject): Promise { - // TODO + public async resolveImage(actor: MiRemoteUser, value: string | IObject): Promise { + // TODO: Misskeyに対象のImageが登録されていればそれを返す // リモートサーバーからフェッチしてきて登録 return await this.createImage(actor, value); diff --git a/packages/backend/src/core/activitypub/models/ApNoteService.ts b/packages/backend/src/core/activitypub/models/ApNoteService.ts index ad7b3b145c..4827baad84 100644 --- a/packages/backend/src/core/activitypub/models/ApNoteService.ts +++ b/packages/backend/src/core/activitypub/models/ApNoteService.ts @@ -4,7 +4,6 @@ */ import { forwardRef, Inject, Injectable } from '@nestjs/common'; -import promiseLimit from 'promise-limit'; import { In } from 'typeorm'; import { DI } from '@/di-symbols.js'; import type { PollsRepository, EmojisRepository, NotesRepository } from '@/models/_.js'; @@ -87,20 +86,20 @@ export class ApNoteService { const expectHost = this.utilityService.extractDbHost(uri); if (!validPost.includes(getApType(object))) { - return new Error(`invalid Note: invalid object type ${getApType(object)}`); + return new IdentifiableError('d450b8a9-48e4-4dab-ae36-f4db763fda7c', `invalid Note: invalid object type ${getApType(object)}`); } if (object.id && this.utilityService.extractDbHost(object.id) !== expectHost) { - return new Error(`invalid Note: id has different host. expected: ${expectHost}, actual: ${this.utilityService.extractDbHost(object.id)}`); + return new IdentifiableError('d450b8a9-48e4-4dab-ae36-f4db763fda7c', `invalid Note: id has different host. expected: ${expectHost}, actual: ${this.utilityService.extractDbHost(object.id)}`); } const actualHost = object.attributedTo && this.utilityService.extractDbHost(getOneApId(object.attributedTo)); if (object.attributedTo && actualHost !== expectHost) { - return new Error(`invalid Note: attributedTo has different host. expected: ${expectHost}, actual: ${actualHost}`); + return new IdentifiableError('d450b8a9-48e4-4dab-ae36-f4db763fda7c', `invalid Note: attributedTo has different host. expected: ${expectHost}, actual: ${actualHost}`); } if (object.published && !this.idService.isSafeT(new Date(object.published).valueOf())) { - return new Error('invalid Note: published timestamp is malformed'); + return new IdentifiableError('d450b8a9-48e4-4dab-ae36-f4db763fda7c', 'invalid Note: published timestamp is malformed'); } return null; @@ -134,7 +133,7 @@ export class ApNoteService { value, object, }); - throw new Error('invalid note'); + throw err; } const note = object as IPost; @@ -214,15 +213,13 @@ export class ApNoteService { } // 添付ファイル - // TODO: attachmentは必ずしもImageではない - // TODO: attachmentは必ずしも配列ではない - const limit = promiseLimit(2); - const files = (await Promise.all(toArray(note.attachment).map(attach => ( - limit(() => this.apImageService.resolveImage(actor, { - ...attach, - sensitive: note.sensitive, // Noteがsensitiveなら添付もsensitiveにする - })) - )))); + const files: MiDriveFile[] = []; + + for (const attach of toArray(note.attachment)) { + attach.sensitive ??= note.sensitive; + const file = await this.apImageService.resolveImage(actor, attach); + if (file) files.push(file); + } // リプライ const reply: MiNote | null = note.inReplyTo @@ -441,15 +438,13 @@ export class ApNoteService { } // 添付ファイル - // TODO: attachmentは必ずしもImageではない - // TODO: attachmentは必ずしも配列ではない - const limit = promiseLimit(2); - const files = (await Promise.all(toArray(note.attachment).map(attach => ( - limit(() => this.apImageService.resolveImage(actor, { - ...attach, - sensitive: note.sensitive, // Noteがsensitiveなら添付もsensitiveにする - })) - )))); + const files: MiDriveFile[] = []; + + for (const attach of toArray(note.attachment)) { + attach.sensitive ??= note.sensitive; + const file = await this.apImageService.resolveImage(actor, attach); + if (file) files.push(file); + } // リプライ const reply: MiNote | null = note.inReplyTo diff --git a/packages/backend/src/core/activitypub/type.ts b/packages/backend/src/core/activitypub/type.ts index 716515840c..8edd8a1aba 100644 --- a/packages/backend/src/core/activitypub/type.ts +++ b/packages/backend/src/core/activitypub/type.ts @@ -25,6 +25,7 @@ export interface IObject { endTime?: Date; icon?: any; image?: any; + mediaType?: string; url?: ApObject | string; href?: string; tag?: IObject | IObject[]; @@ -246,14 +247,14 @@ export interface IKey extends IObject { } export interface IApDocument extends IObject { - type: 'Document'; - name: string | null; - mediaType: string; + type: 'Audio' | 'Document' | 'Image' | 'Page' | 'Video'; } -export interface IApImage extends IObject { +export const isDocument = (object: IObject): object is IApDocument => + ['Audio', 'Document', 'Image', 'Page', 'Video'].includes(getApType(object)); + +export interface IApImage extends IApDocument { type: 'Image'; - name: string | null; } export interface ICreate extends IActivity { @@ -333,3 +334,4 @@ export const isAnnounce = (object: IObject): object is IAnnounce => getApType(ob export const isBlock = (object: IObject): object is IBlock => getApType(object) === 'Block'; export const isFlag = (object: IObject): object is IFlag => getApType(object) === 'Flag'; export const isMove = (object: IObject): object is IMove => getApType(object) === 'Move'; +export const isNote = (object: IObject): object is IPost => getApType(object) === 'Note'; diff --git a/packages/backend/src/core/chart/charts/federation.ts b/packages/backend/src/core/chart/charts/federation.ts index 5e4555ee96..28e441d72c 100644 --- a/packages/backend/src/core/chart/charts/federation.ts +++ b/packages/backend/src/core/chart/charts/federation.ts @@ -47,7 +47,7 @@ export default class FederationChart extends Chart { // eslint-di const suspendedInstancesQuery = this.instancesRepository.createQueryBuilder('instance') .select('instance.host') - .where('instance.isSuspended = true'); + .where("instance.suspensionState != 'none'"); const pubsubSubQuery = this.followingsRepository.createQueryBuilder('f') .select('f.followerHost') @@ -89,7 +89,7 @@ export default class FederationChart extends Chart { // eslint-di .select('COUNT(instance.id)') .where(`instance.host IN (${ subInstancesQuery.getQuery() })`) .andWhere(meta.blockedHosts.length === 0 ? '1=1' : 'instance.host NOT ILIKE ANY(ARRAY[:...blocked])', { blocked: meta.blockedHosts.flatMap(x => [x, `%.${x}`]) }) - .andWhere('instance.isSuspended = false') + .andWhere("instance.suspensionState = 'none'") .andWhere('instance.isNotResponding = false') .getRawOne() .then(x => parseInt(x.count, 10)), @@ -97,7 +97,7 @@ export default class FederationChart extends Chart { // eslint-di .select('COUNT(instance.id)') .where(`instance.host IN (${ pubInstancesQuery.getQuery() })`) .andWhere(meta.blockedHosts.length === 0 ? '1=1' : 'instance.host NOT ILIKE ANY(ARRAY[:...blocked])', { blocked: meta.blockedHosts.flatMap(x => [x, `%.${x}`]) }) - .andWhere('instance.isSuspended = false') + .andWhere("instance.suspensionState = 'none'") .andWhere('instance.isNotResponding = false') .getRawOne() .then(x => parseInt(x.count, 10)), diff --git a/packages/backend/src/core/chart/core.ts b/packages/backend/src/core/chart/core.ts index aa0cb9dc2b..f10e30ef10 100644 --- a/packages/backend/src/core/chart/core.ts +++ b/packages/backend/src/core/chart/core.ts @@ -459,13 +459,15 @@ export default abstract class Chart { } } - // bake unique count + // bake cardinality for (const [k, v] of Object.entries(finalDiffs)) { if (this.schema[k].uniqueIncrement) { const name = COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof Columns; const tempColumnName = UNIQUE_TEMP_COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof TempColumnsForUnique; - queryForHour[name] = new Set([...(v as string[]), ...(logHour[tempColumnName] as unknown as string[])]).size; - queryForDay[name] = new Set([...(v as string[]), ...(logDay[tempColumnName] as unknown as string[])]).size; + const cardinalityOfHour = new Set([...(v as string[]), ...(logHour[tempColumnName] as unknown as string[])]).size; + const cardinalityOfDay = new Set([...(v as string[]), ...(logDay[tempColumnName] as unknown as string[])]).size; + queryForHour[name] = cardinalityOfHour; + queryForDay[name] = cardinalityOfDay; } } @@ -637,7 +639,7 @@ export default abstract class Chart { // 要求された範囲にログがひとつもなかったら if (logs.length === 0) { // もっとも新しいログを持ってくる - // (すくなくともひとつログが無いと隙間埋めできないため) + // (すくなくともひとつログが無いと補間できないため) const recentLog = await repository.findOne({ where: group ? { group: group, @@ -654,7 +656,7 @@ export default abstract class Chart { // 要求された範囲の最も古い箇所に位置するログが存在しなかったら } else if (!isTimeSame(new Date(logs.at(-1)!.date * 1000), gt)) { // 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する - // (隙間埋めできないため) + // (補間できないため) const outdatedLog = await repository.findOne({ where: { date: LessThan(Chart.dateToTimestamp(gt)), @@ -683,7 +685,7 @@ export default abstract class Chart { if (log) { chart.unshift(this.convertRawRecord(log)); } else { - // 隙間埋め + // 補間 const latest = logs.find(l => isTimeBefore(new Date(l.date * 1000), current)); const data = latest ? this.convertRawRecord(latest) : null; chart.unshift(this.getNewLog(data)); diff --git a/packages/backend/src/core/entities/AbuseUserReportEntityService.ts b/packages/backend/src/core/entities/AbuseUserReportEntityService.ts index 49f256d870..b0e1d1ab36 100644 --- a/packages/backend/src/core/entities/AbuseUserReportEntityService.ts +++ b/packages/backend/src/core/entities/AbuseUserReportEntityService.ts @@ -10,6 +10,8 @@ import { awaitAll } from '@/misc/prelude/await-all.js'; import type { MiAbuseUserReport } from '@/models/AbuseUserReport.js'; import { bindThis } from '@/decorators.js'; import { IdService } from '@/core/IdService.js'; +import { isNotNull } from '@/misc/is-not-null.js'; +import type { Packed } from '@/misc/json-schema.js'; import { UserEntityService } from './UserEntityService.js'; @Injectable() @@ -26,6 +28,11 @@ export class AbuseUserReportEntityService { @bindThis public async pack( src: MiAbuseUserReport['id'] | MiAbuseUserReport, + hint?: { + packedReporter?: Packed<'UserDetailedNotMe'>, + packedTargetUser?: Packed<'UserDetailedNotMe'>, + packedAssignee?: Packed<'UserDetailedNotMe'>, + }, ) { const report = typeof src === 'object' ? src : await this.abuseUserReportsRepository.findOneByOrFail({ id: src }); @@ -37,13 +44,13 @@ export class AbuseUserReportEntityService { reporterId: report.reporterId, targetUserId: report.targetUserId, assigneeId: report.assigneeId, - reporter: this.userEntityService.pack(report.reporter ?? report.reporterId, null, { + reporter: hint?.packedReporter ?? this.userEntityService.pack(report.reporter ?? report.reporterId, null, { schema: 'UserDetailedNotMe', }), - targetUser: this.userEntityService.pack(report.targetUser ?? report.targetUserId, null, { + targetUser: hint?.packedTargetUser ?? this.userEntityService.pack(report.targetUser ?? report.targetUserId, null, { schema: 'UserDetailedNotMe', }), - assignee: report.assigneeId ? this.userEntityService.pack(report.assignee ?? report.assigneeId, null, { + assignee: report.assigneeId ? hint?.packedAssignee ?? this.userEntityService.pack(report.assignee ?? report.assigneeId, null, { schema: 'UserDetailedNotMe', }) : null, forwarded: report.forwarded, @@ -51,9 +58,24 @@ export class AbuseUserReportEntityService { } @bindThis - public packMany( - reports: any[], + public async packMany( + reports: MiAbuseUserReport[], ) { - return Promise.all(reports.map(x => this.pack(x))); + const _reporters = reports.map(({ reporter, reporterId }) => reporter ?? reporterId); + const _targetUsers = reports.map(({ targetUser, targetUserId }) => targetUser ?? targetUserId); + const _assignees = reports.map(({ assignee, assigneeId }) => assignee ?? assigneeId).filter(isNotNull); + const _userMap = await this.userEntityService.packMany( + [..._reporters, ..._targetUsers, ..._assignees], + null, + { schema: 'UserDetailedNotMe' }, + ).then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + reports.map(report => { + const packedReporter = _userMap.get(report.reporterId); + const packedTargetUser = _userMap.get(report.targetUserId); + const packedAssignee = report.assigneeId != null ? _userMap.get(report.assigneeId) : undefined; + return this.pack(report, { packedReporter, packedTargetUser, packedAssignee }); + }), + ); } } diff --git a/packages/backend/src/core/entities/AnnouncementEntityService.ts b/packages/backend/src/core/entities/AnnouncementEntityService.ts new file mode 100644 index 0000000000..90b04d0229 --- /dev/null +++ b/packages/backend/src/core/entities/AnnouncementEntityService.ts @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Inject, Injectable } from '@nestjs/common'; +import { DI } from '@/di-symbols.js'; +import type { AnnouncementsRepository, AnnouncementReadsRepository, MiAnnouncement, MiUser } from '@/models/_.js'; +import type { Packed } from '@/misc/json-schema.js'; +import { bindThis } from '@/decorators.js'; +import { IdService } from '@/core/IdService.js'; + +@Injectable() +export class AnnouncementEntityService { + constructor( + @Inject(DI.announcementsRepository) + private announcementsRepository: AnnouncementsRepository, + + @Inject(DI.announcementReadsRepository) + private announcementReadsRepository: AnnouncementReadsRepository, + + private idService: IdService, + ) { + } + + @bindThis + public async pack( + src: MiAnnouncement['id'] | MiAnnouncement & { isRead?: boolean | null }, + me?: { id: MiUser['id'] } | null | undefined, + ): Promise> { + const announcement = typeof src === 'object' + ? src + : await this.announcementsRepository.findOneByOrFail({ + id: src, + }) as MiAnnouncement & { isRead?: boolean | null }; + + if (me && announcement.isRead === undefined) { + announcement.isRead = await this.announcementReadsRepository + .countBy({ + announcementId: announcement.id, + userId: me.id, + }) + .then((count: number) => count > 0); + } + + return { + id: announcement.id, + createdAt: this.idService.parse(announcement.id).date.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, + silence: announcement.silence, + isRead: announcement.isRead !== null ? announcement.isRead : undefined, + }; + } + + @bindThis + public async packMany( + announcements: (MiAnnouncement['id'] | MiAnnouncement & { isRead?: boolean | null } | MiAnnouncement)[], + me?: { id: MiUser['id'] } | null | undefined, + ) : Promise[]> { + return (await Promise.allSettled(announcements.map(x => this.pack(x, me)))) + .filter(result => result.status === 'fulfilled') + .map(result => (result as PromiseFulfilledResult>).value); + } +} diff --git a/packages/backend/src/core/entities/AntennaEntityService.ts b/packages/backend/src/core/entities/AntennaEntityService.ts index 64d6a3c978..e770028af3 100644 --- a/packages/backend/src/core/entities/AntennaEntityService.ts +++ b/packages/backend/src/core/entities/AntennaEntityService.ts @@ -38,11 +38,12 @@ export class AntennaEntityService { users: antenna.users, caseSensitive: antenna.caseSensitive, localOnly: antenna.localOnly, - notify: antenna.notify, + excludeBots: antenna.excludeBots, withReplies: antenna.withReplies, withFile: antenna.withFile, isActive: antenna.isActive, hasUnreadNote: false, // TODO + notify: false, // 後方互換性のため }; } } diff --git a/packages/backend/src/core/entities/BlockingEntityService.ts b/packages/backend/src/core/entities/BlockingEntityService.ts index c8c1520ceb..1e699032e2 100644 --- a/packages/backend/src/core/entities/BlockingEntityService.ts +++ b/packages/backend/src/core/entities/BlockingEntityService.ts @@ -29,6 +29,9 @@ export class BlockingEntityService { public async pack( src: MiBlocking['id'] | MiBlocking, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + blockee?: Packed<'UserDetailedNotMe'>, + }, ): Promise> { const blocking = typeof src === 'object' ? src : await this.blockingsRepository.findOneByOrFail({ id: src }); @@ -36,17 +39,20 @@ export class BlockingEntityService { id: blocking.id, createdAt: this.idService.parse(blocking.id).date.toISOString(), blockeeId: blocking.blockeeId, - blockee: this.userEntityService.pack(blocking.blockeeId, me, { + blockee: hint?.blockee ?? this.userEntityService.pack(blocking.blockeeId, me, { schema: 'UserDetailedNotMe', }), }); } @bindThis - public packMany( - blockings: any[], + public async packMany( + blockings: MiBlocking[], me: { id: MiUser['id'] }, ) { - return Promise.all(blockings.map(x => this.pack(x, me))); + const _blockees = blockings.map(({ blockee, blockeeId }) => blockee ?? blockeeId); + const _userMap = await this.userEntityService.packMany(_blockees, me, { schema: 'UserDetailedNotMe' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(blockings.map(blocking => this.pack(blocking, me, { blockee: _userMap.get(blocking.blockeeId) }))); } } diff --git a/packages/backend/src/core/entities/ClipEntityService.ts b/packages/backend/src/core/entities/ClipEntityService.ts index 26fcd6714d..3855a28436 100644 --- a/packages/backend/src/core/entities/ClipEntityService.ts +++ b/packages/backend/src/core/entities/ClipEntityService.ts @@ -5,7 +5,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { DI } from '@/di-symbols.js'; -import type { ClipFavoritesRepository, ClipsRepository, MiUser } from '@/models/_.js'; +import type { ClipNotesRepository, ClipFavoritesRepository, ClipsRepository, MiUser } from '@/models/_.js'; import { awaitAll } from '@/misc/prelude/await-all.js'; import type { Packed } from '@/misc/json-schema.js'; import type { } from '@/models/Blocking.js'; @@ -20,6 +20,9 @@ export class ClipEntityService { @Inject(DI.clipsRepository) private clipsRepository: ClipsRepository, + @Inject(DI.clipNotesRepository) + private clipNotesRepository: ClipNotesRepository, + @Inject(DI.clipFavoritesRepository) private clipFavoritesRepository: ClipFavoritesRepository, @@ -32,6 +35,9 @@ export class ClipEntityService { public async pack( src: MiClip['id'] | MiClip, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + packedUser?: Packed<'UserLite'> + }, ): Promise> { const meId = me ? me.id : null; const clip = typeof src === 'object' ? src : await this.clipsRepository.findOneByOrFail({ id: src }); @@ -41,21 +47,25 @@ export class ClipEntityService { createdAt: this.idService.parse(clip.id).date.toISOString(), lastClippedAt: clip.lastClippedAt ? clip.lastClippedAt.toISOString() : null, userId: clip.userId, - user: this.userEntityService.pack(clip.user ?? clip.userId), + user: hint?.packedUser ?? this.userEntityService.pack(clip.user ?? clip.userId), name: clip.name, description: clip.description, isPublic: clip.isPublic, favoritedCount: await this.clipFavoritesRepository.countBy({ clipId: clip.id }), isFavorited: meId ? await this.clipFavoritesRepository.exists({ where: { clipId: clip.id, userId: meId } }) : undefined, + notesCount: meId ? await this.clipNotesRepository.countBy({ clipId: clip.id }) : undefined, }); } @bindThis - public packMany( + public async packMany( clips: MiClip[], me?: { id: MiUser['id'] } | null | undefined, ) { - return Promise.all(clips.map(x => this.pack(x, me))); + const _users = clips.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(clips.map(clip => this.pack(clip, me, { packedUser: _userMap.get(clip.userId) }))); } } diff --git a/packages/backend/src/core/entities/DriveFileEntityService.ts b/packages/backend/src/core/entities/DriveFileEntityService.ts index 8affe2b3bf..02ff2e7754 100644 --- a/packages/backend/src/core/entities/DriveFileEntityService.ts +++ b/packages/backend/src/core/entities/DriveFileEntityService.ts @@ -222,6 +222,9 @@ export class DriveFileEntityService { public async packNullable( src: MiDriveFile['id'] | MiDriveFile, options?: PackOptions, + hint?: { + packedUser?: Packed<'UserLite'> + }, ): Promise | null> { const opts = Object.assign({ detail: false, @@ -248,8 +251,8 @@ export class DriveFileEntityService { folder: opts.detail && file.folderId ? this.driveFolderEntityService.pack(file.folderId, { detail: true, }) : null, - userId: opts.withUser ? file.userId : null, - user: (opts.withUser && file.userId) ? this.userEntityService.pack(file.userId) : null, + userId: file.userId, + user: (opts.withUser && file.userId) ? hint?.packedUser ?? this.userEntityService.pack(file.userId) : null, }); } @@ -258,7 +261,10 @@ export class DriveFileEntityService { files: MiDriveFile[], options?: PackOptions, ): Promise[]> { - const items = await Promise.all(files.map(f => this.packNullable(f, options))); + const _user = files.map(({ user, userId }) => user ?? userId).filter(isNotNull); + const _userMap = await this.userEntityService.packMany(_user) + .then(users => new Map(users.map(user => [user.id, user]))); + const items = await Promise.all(files.map(f => this.packNullable(f, options, f.userId ? { packedUser: _userMap.get(f.userId) } : {}))); return items.filter(isNotNull); } diff --git a/packages/backend/src/core/entities/FlashEntityService.ts b/packages/backend/src/core/entities/FlashEntityService.ts index db4cf6d360..d110f7afc6 100644 --- a/packages/backend/src/core/entities/FlashEntityService.ts +++ b/packages/backend/src/core/entities/FlashEntityService.ts @@ -33,6 +33,9 @@ export class FlashEntityService { public async pack( src: MiFlash['id'] | MiFlash, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + packedUser?: Packed<'UserLite'> + }, ): Promise> { const meId = me ? me.id : null; const flash = typeof src === 'object' ? src : await this.flashsRepository.findOneByOrFail({ id: src }); @@ -42,7 +45,7 @@ export class FlashEntityService { createdAt: this.idService.parse(flash.id).date.toISOString(), updatedAt: flash.updatedAt.toISOString(), userId: flash.userId, - user: this.userEntityService.pack(flash.user ?? flash.userId, me), // { schema: 'UserDetailed' } すると無限ループするので注意 + user: hint?.packedUser ?? this.userEntityService.pack(flash.user ?? flash.userId, me), // { schema: 'UserDetailed' } すると無限ループするので注意 title: flash.title, summary: flash.summary, script: flash.script, @@ -52,11 +55,14 @@ export class FlashEntityService { } @bindThis - public packMany( - flashs: MiFlash[], + public async packMany( + flashes: MiFlash[], me?: { id: MiUser['id'] } | null | undefined, ) { - return Promise.all(flashs.map(x => this.pack(x, me))); + const _users = flashes.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(flashes.map(flash => this.pack(flash, me, { packedUser: _userMap.get(flash.userId) }))); } } diff --git a/packages/backend/src/core/entities/FollowRequestEntityService.ts b/packages/backend/src/core/entities/FollowRequestEntityService.ts index 763b75101f..0101ec8aa7 100644 --- a/packages/backend/src/core/entities/FollowRequestEntityService.ts +++ b/packages/backend/src/core/entities/FollowRequestEntityService.ts @@ -10,6 +10,7 @@ import type { } from '@/models/Blocking.js'; import type { MiUser } from '@/models/User.js'; import type { MiFollowRequest } from '@/models/FollowRequest.js'; import { bindThis } from '@/decorators.js'; +import type { Packed } from '@/misc/json-schema.js'; import { UserEntityService } from './UserEntityService.js'; @Injectable() @@ -26,14 +27,36 @@ export class FollowRequestEntityService { public async pack( src: MiFollowRequest['id'] | MiFollowRequest, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + packedFollower?: Packed<'UserLite'>, + packedFollowee?: Packed<'UserLite'>, + }, ) { const request = typeof src === 'object' ? src : await this.followRequestsRepository.findOneByOrFail({ id: src }); return { id: request.id, - follower: await this.userEntityService.pack(request.followerId, me), - followee: await this.userEntityService.pack(request.followeeId, me), + follower: hint?.packedFollower ?? await this.userEntityService.pack(request.followerId, me), + followee: hint?.packedFollowee ?? await this.userEntityService.pack(request.followeeId, me), }; } + + @bindThis + public async packMany( + requests: MiFollowRequest[], + me?: { id: MiUser['id'] } | null | undefined, + ) { + const _followers = requests.map(({ follower, followerId }) => follower ?? followerId); + const _followees = requests.map(({ followee, followeeId }) => followee ?? followeeId); + const _userMap = await this.userEntityService.packMany([..._followers, ..._followees], me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + requests.map(req => { + const packedFollower = _userMap.get(req.followerId); + const packedFollowee = _userMap.get(req.followeeId); + return this.pack(req, me, { packedFollower, packedFollowee }); + }), + ); + } } diff --git a/packages/backend/src/core/entities/FollowingEntityService.ts b/packages/backend/src/core/entities/FollowingEntityService.ts index 24cd33e3f7..d2dbaf2270 100644 --- a/packages/backend/src/core/entities/FollowingEntityService.ts +++ b/packages/backend/src/core/entities/FollowingEntityService.ts @@ -78,6 +78,10 @@ export class FollowingEntityService { populateFollowee?: boolean; populateFollower?: boolean; }, + hint?: { + packedFollowee?: Packed<'UserDetailedNotMe'>, + packedFollower?: Packed<'UserDetailedNotMe'>, + }, ): Promise> { const following = typeof src === 'object' ? src : await this.followingsRepository.findOneByOrFail({ id: src }); @@ -88,25 +92,35 @@ export class FollowingEntityService { createdAt: this.idService.parse(following.id).date.toISOString(), followeeId: following.followeeId, followerId: following.followerId, - followee: opts.populateFollowee ? this.userEntityService.pack(following.followee ?? following.followeeId, me, { + followee: opts.populateFollowee ? hint?.packedFollowee ?? this.userEntityService.pack(following.followee ?? following.followeeId, me, { schema: 'UserDetailedNotMe', }) : undefined, - follower: opts.populateFollower ? this.userEntityService.pack(following.follower ?? following.followerId, me, { + follower: opts.populateFollower ? hint?.packedFollower ?? this.userEntityService.pack(following.follower ?? following.followerId, me, { schema: 'UserDetailedNotMe', }) : undefined, }); } @bindThis - public packMany( - followings: any[], + public async packMany( + followings: MiFollowing[], me?: { id: MiUser['id'] } | null | undefined, opts?: { populateFollowee?: boolean; populateFollower?: boolean; }, ) { - return Promise.all(followings.map(x => this.pack(x, me, opts))); + const _followees = opts?.populateFollowee ? followings.map(({ followee, followeeId }) => followee ?? followeeId) : []; + const _followers = opts?.populateFollower ? followings.map(({ follower, followerId }) => follower ?? followerId) : []; + const _userMap = await this.userEntityService.packMany([..._followees, ..._followers], me, { schema: 'UserDetailedNotMe' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + followings.map(following => { + const packedFollowee = opts?.populateFollowee ? _userMap.get(following.followeeId) : undefined; + const packedFollower = opts?.populateFollower ? _userMap.get(following.followerId) : undefined; + return this.pack(following, me, opts, { packedFollowee, packedFollower }); + }), + ); } } diff --git a/packages/backend/src/core/entities/GalleryPostEntityService.ts b/packages/backend/src/core/entities/GalleryPostEntityService.ts index 101182a9e5..9746a4c1af 100644 --- a/packages/backend/src/core/entities/GalleryPostEntityService.ts +++ b/packages/backend/src/core/entities/GalleryPostEntityService.ts @@ -35,6 +35,9 @@ export class GalleryPostEntityService { public async pack( src: MiGalleryPost['id'] | MiGalleryPost, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + packedUser?: Packed<'UserLite'> + }, ): Promise> { const meId = me ? me.id : null; const post = typeof src === 'object' ? src : await this.galleryPostsRepository.findOneByOrFail({ id: src }); @@ -44,7 +47,7 @@ export class GalleryPostEntityService { createdAt: this.idService.parse(post.id).date.toISOString(), updatedAt: post.updatedAt.toISOString(), userId: post.userId, - user: this.userEntityService.pack(post.user ?? post.userId, me), + user: hint?.packedUser ?? this.userEntityService.pack(post.user ?? post.userId, me), title: post.title, description: post.description, fileIds: post.fileIds, @@ -58,11 +61,14 @@ export class GalleryPostEntityService { } @bindThis - public packMany( + public async packMany( posts: MiGalleryPost[], me?: { id: MiUser['id'] } | null | undefined, ) { - return Promise.all(posts.map(x => this.pack(x, me))); + const _users = posts.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(posts.map(post => this.pack(post, me, { packedUser: _userMap.get(post.userId) }))); } } diff --git a/packages/backend/src/core/entities/InstanceEntityService.ts b/packages/backend/src/core/entities/InstanceEntityService.ts index b4a518a1c6..002a93397d 100644 --- a/packages/backend/src/core/entities/InstanceEntityService.ts +++ b/packages/backend/src/core/entities/InstanceEntityService.ts @@ -39,7 +39,8 @@ export class InstanceEntityService { followingCount: instance.followingCount, followersCount: instance.followersCount, isNotResponding: instance.isNotResponding, - isSuspended: instance.isSuspended, + isSuspended: instance.suspensionState !== 'none', + suspensionState: instance.suspensionState, isBlocked: this.utilityService.isBlockedHost(meta.blockedHosts, instance.host), softwareName: instance.softwareName, softwareVersion: instance.softwareVersion, diff --git a/packages/backend/src/core/entities/InviteCodeEntityService.ts b/packages/backend/src/core/entities/InviteCodeEntityService.ts index 891543bc0f..26f57e1299 100644 --- a/packages/backend/src/core/entities/InviteCodeEntityService.ts +++ b/packages/backend/src/core/entities/InviteCodeEntityService.ts @@ -12,6 +12,7 @@ import type { MiUser } from '@/models/User.js'; import type { MiRegistrationTicket } from '@/models/RegistrationTicket.js'; import { bindThis } from '@/decorators.js'; import { IdService } from '@/core/IdService.js'; +import { isNotNull } from '@/misc/is-not-null.js'; import { UserEntityService } from './UserEntityService.js'; @Injectable() @@ -29,6 +30,10 @@ export class InviteCodeEntityService { public async pack( src: MiRegistrationTicket['id'] | MiRegistrationTicket, me?: { id: MiUser['id'] } | null | undefined, + hints?: { + packedCreatedBy?: Packed<'UserLite'>, + packedUsedBy?: Packed<'UserLite'>, + }, ): Promise> { const target = typeof src === 'object' ? src : await this.registrationTicketsRepository.findOneOrFail({ where: { @@ -42,18 +47,28 @@ export class InviteCodeEntityService { code: target.code, expiresAt: target.expiresAt ? target.expiresAt.toISOString() : null, createdAt: this.idService.parse(target.id).date.toISOString(), - createdBy: target.createdBy ? await this.userEntityService.pack(target.createdBy, me) : null, - usedBy: target.usedBy ? await this.userEntityService.pack(target.usedBy, me) : null, + createdBy: target.createdBy ? hints?.packedCreatedBy ?? await this.userEntityService.pack(target.createdBy, me) : null, + usedBy: target.usedBy ? hints?.packedUsedBy ?? await this.userEntityService.pack(target.usedBy, me) : null, usedAt: target.usedAt ? target.usedAt.toISOString() : null, used: !!target.usedAt, }); } @bindThis - public packMany( - targets: any[], + public async packMany( + tickets: MiRegistrationTicket[], me: { id: MiUser['id'] }, ) { - return Promise.all(targets.map(x => this.pack(x, me))); + const _createdBys = tickets.map(({ createdBy, createdById }) => createdBy ?? createdById).filter(isNotNull); + const _usedBys = tickets.map(({ usedBy, usedById }) => usedBy ?? usedById).filter(isNotNull); + const _userMap = await this.userEntityService.packMany([..._createdBys, ..._usedBys], me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + tickets.map(ticket => { + const packedCreatedBy = ticket.createdById != null ? _userMap.get(ticket.createdById) : undefined; + const packedUsedBy = ticket.usedById != null ? _userMap.get(ticket.usedById) : undefined; + return this.pack(ticket, me, { packedCreatedBy, packedUsedBy }); + }), + ); } } diff --git a/packages/backend/src/core/entities/MetaEntityService.ts b/packages/backend/src/core/entities/MetaEntityService.ts index 7e3926c431..34d46e50e5 100644 --- a/packages/backend/src/core/entities/MetaEntityService.ts +++ b/packages/backend/src/core/entities/MetaEntityService.ts @@ -67,6 +67,7 @@ export class MetaEntityService { impressumUrl: instance.impressumUrl, donationUrl: instance.donationUrl, privacyPolicyUrl: instance.privacyPolicyUrl, + inquiryUrl: instance.inquiryUrl, disableRegistration: instance.disableRegistration, emailRequiredForSignup: instance.emailRequiredForSignup, approvalRequiredForSignup: instance.approvalRequiredForSignup, @@ -114,6 +115,7 @@ export class MetaEntityService { policies: { ...DEFAULT_POLICIES, ...instance.policies }, mediaProxy: this.config.mediaProxy, + enableUrlPreview: instance.urlPreviewEnabled, }; return packed; diff --git a/packages/backend/src/core/entities/ModerationLogEntityService.ts b/packages/backend/src/core/entities/ModerationLogEntityService.ts index 205e147bd1..bf1b2a002c 100644 --- a/packages/backend/src/core/entities/ModerationLogEntityService.ts +++ b/packages/backend/src/core/entities/ModerationLogEntityService.ts @@ -8,9 +8,10 @@ import { DI } from '@/di-symbols.js'; import type { ModerationLogsRepository } from '@/models/_.js'; import { awaitAll } from '@/misc/prelude/await-all.js'; import type { } from '@/models/Blocking.js'; -import type { MiModerationLog } from '@/models/ModerationLog.js'; +import { MiModerationLog } from '@/models/ModerationLog.js'; import { bindThis } from '@/decorators.js'; import { IdService } from '@/core/IdService.js'; +import type { Packed } from '@/misc/json-schema.js'; import { UserEntityService } from './UserEntityService.js'; @Injectable() @@ -27,6 +28,9 @@ export class ModerationLogEntityService { @bindThis public async pack( src: MiModerationLog['id'] | MiModerationLog, + hint?: { + packedUser?: Packed<'UserDetailedNotMe'>, + }, ) { const log = typeof src === 'object' ? src : await this.moderationLogsRepository.findOneByOrFail({ id: src }); @@ -36,17 +40,20 @@ export class ModerationLogEntityService { type: log.type, info: log.info, userId: log.userId, - user: this.userEntityService.pack(log.user ?? log.userId, null, { + user: hint?.packedUser ?? this.userEntityService.pack(log.user ?? log.userId, null, { schema: 'UserDetailedNotMe', }), }); } @bindThis - public packMany( - reports: any[], + public async packMany( + reports: MiModerationLog[], ) { - return Promise.all(reports.map(x => this.pack(x))); + const _users = reports.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, null, { schema: 'UserDetailedNotMe' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(reports.map(report => this.pack(report, { packedUser: _userMap.get(report.userId) }))); } } diff --git a/packages/backend/src/core/entities/MutingEntityService.ts b/packages/backend/src/core/entities/MutingEntityService.ts index 0a52f429a2..d361a20271 100644 --- a/packages/backend/src/core/entities/MutingEntityService.ts +++ b/packages/backend/src/core/entities/MutingEntityService.ts @@ -30,6 +30,9 @@ export class MutingEntityService { public async pack( src: MiMuting['id'] | MiMuting, me?: { id: MiUser['id'] } | null | undefined, + hints?: { + packedMutee?: Packed<'UserDetailedNotMe'>, + }, ): Promise> { const muting = typeof src === 'object' ? src : await this.mutingsRepository.findOneByOrFail({ id: src }); @@ -38,18 +41,21 @@ export class MutingEntityService { createdAt: this.idService.parse(muting.id).date.toISOString(), expiresAt: muting.expiresAt ? muting.expiresAt.toISOString() : null, muteeId: muting.muteeId, - mutee: this.userEntityService.pack(muting.muteeId, me, { + mutee: hints?.packedMutee ?? this.userEntityService.pack(muting.muteeId, me, { schema: 'UserDetailedNotMe', }), }); } @bindThis - public packMany( - mutings: any[], + public async packMany( + mutings: MiMuting[], me: { id: MiUser['id'] }, ) { - return Promise.all(mutings.map(x => this.pack(x, me))); + const _mutees = mutings.map(({ mutee, muteeId }) => mutee ?? muteeId); + const _userMap = await this.userEntityService.packMany(_mutees, me, { schema: 'UserDetailedNotMe' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(mutings.map(muting => this.pack(muting, me, { packedMutee: _userMap.get(muting.muteeId) }))); } } diff --git a/packages/backend/src/core/entities/NoteEntityService.ts b/packages/backend/src/core/entities/NoteEntityService.ts index 86a8670f29..ca755ea286 100644 --- a/packages/backend/src/core/entities/NoteEntityService.ts +++ b/packages/backend/src/core/entities/NoteEntityService.ts @@ -307,6 +307,7 @@ export class NoteEntityService implements OnModuleInit { _hint_?: { myReactions: Map; packedFiles: Map | null>; + packedUsers: Map> }; }, ): Promise> { @@ -336,13 +337,14 @@ export class NoteEntityService implements OnModuleInit { .filter(x => x.startsWith(':') && x.includes('@') && !x.includes('@.')) // リモートカスタム絵文字のみ .map(x => this.reactionService.decodeReaction(x).reaction.replaceAll(':', '')); const packedFiles = options?._hint_?.packedFiles; + const packedUsers = options?._hint_?.packedUsers; const packed: Packed<'Note'> = await awaitAll({ id: note.id, createdAt: this.idService.parse(note.id).date.toISOString(), updatedAt: note.updatedAt ? note.updatedAt.toISOString() : undefined, userId: note.userId, - user: this.userEntityService.pack(note.user ?? note.userId, me), + user: packedUsers?.get(note.userId) ?? this.userEntityService.pack(note.user ?? note.userId, me), text: text, cw: note.cw, visibility: note.visibility, @@ -351,6 +353,7 @@ export class NoteEntityService implements OnModuleInit { visibleUserIds: note.visibility === 'specified' ? note.visibleUserIds : undefined, renoteCount: note.renoteCount, repliesCount: note.repliesCount, + reactionCount: Object.values(note.reactions).reduce((a, b) => a + b, 0), reactions: this.reactionService.convertLegacyReactions(note.reactions), reactionEmojis: this.customEmojiService.populateEmojis(reactionEmojiNames, host), reactionAndUserPairCache: opts.withReactionAndUserPairCache ? note.reactionAndUserPairCache : undefined, @@ -464,12 +467,20 @@ export class NoteEntityService implements OnModuleInit { // TODO: 本当は renote とか reply がないのに renoteId とか replyId があったらここで解決しておく const fileIds = notes.map(n => [n.fileIds, n.renote?.fileIds, n.reply?.fileIds]).flat(2).filter(isNotNull); const packedFiles = fileIds.length > 0 ? await this.driveFileEntityService.packManyByIdsMap(fileIds) : new Map(); + const users = [ + ...notes.map(({ user, userId }) => user ?? userId), + ...notes.map(({ replyUserId }) => replyUserId).filter(isNotNull), + ...notes.map(({ renoteUserId }) => renoteUserId).filter(isNotNull), + ]; + const packedUsers = await this.userEntityService.packMany(users, me) + .then(users => new Map(users.map(u => [u.id, u]))); return await Promise.all(notes.map(n => this.pack(n, me, { ...options, _hint_: { myReactions: myReactionsMap, packedFiles, + packedUsers, }, }))); } diff --git a/packages/backend/src/core/entities/NoteReactionEntityService.ts b/packages/backend/src/core/entities/NoteReactionEntityService.ts index 3f4fa3cf96..46ec13704c 100644 --- a/packages/backend/src/core/entities/NoteReactionEntityService.ts +++ b/packages/backend/src/core/entities/NoteReactionEntityService.ts @@ -52,6 +52,9 @@ export class NoteReactionEntityService implements OnModuleInit { options?: { withNote: boolean; }, + hints?: { + packedUser?: Packed<'UserLite'> + }, ): Promise> { const opts = Object.assign({ withNote: false, @@ -62,7 +65,7 @@ export class NoteReactionEntityService implements OnModuleInit { return { id: reaction.id, createdAt: this.idService.parse(reaction.id).date.toISOString(), - user: await this.userEntityService.pack(reaction.user ?? reaction.userId, me), + user: hints?.packedUser ?? await this.userEntityService.pack(reaction.user ?? reaction.userId, me), type: this.reactionService.convertLegacyReaction(reaction.reaction), ...(opts.withNote ? { note: await this.noteEntityService.pack(reaction.note ?? reaction.noteId, me), @@ -81,7 +84,9 @@ export class NoteReactionEntityService implements OnModuleInit { const opts = Object.assign({ withNote: false, }, options); - - return Promise.all(reactions.map(reaction => this.pack(reaction, me, opts))); + const _users = reactions.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(reactions.map(reaction => this.pack(reaction, me, opts, { packedUser: _userMap.get(reaction.userId) }))); } } diff --git a/packages/backend/src/core/entities/PageEntityService.ts b/packages/backend/src/core/entities/PageEntityService.ts index 65c69a49a7..142d9e81db 100644 --- a/packages/backend/src/core/entities/PageEntityService.ts +++ b/packages/backend/src/core/entities/PageEntityService.ts @@ -40,6 +40,9 @@ export class PageEntityService { public async pack( src: MiPage['id'] | MiPage, me?: { id: MiUser['id'] } | null | undefined, + hint?: { + packedUser?: Packed<'UserLite'> + }, ): Promise> { const meId = me ? me.id : null; const page = typeof src === 'object' ? src : await this.pagesRepository.findOneByOrFail({ id: src }); @@ -91,7 +94,7 @@ export class PageEntityService { createdAt: this.idService.parse(page.id).date.toISOString(), updatedAt: page.updatedAt.toISOString(), userId: page.userId, - user: this.userEntityService.pack(page.user ?? page.userId, me), // { schema: 'UserDetailed' } すると無限ループするので注意 + user: hint?.packedUser ?? this.userEntityService.pack(page.user ?? page.userId, me), // { schema: 'UserDetailed' } すると無限ループするので注意 content: page.content, variables: page.variables, title: page.title, @@ -110,11 +113,14 @@ export class PageEntityService { } @bindThis - public packMany( + public async packMany( pages: MiPage[], me?: { id: MiUser['id'] } | null | undefined, ) { - return Promise.all(pages.map(x => this.pack(x, me))); + const _users = pages.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(pages.map(page => this.pack(page, me, { packedUser: _userMap.get(page.userId) }))); } } diff --git a/packages/backend/src/core/entities/RenoteMutingEntityService.ts b/packages/backend/src/core/entities/RenoteMutingEntityService.ts index 0b05a5db80..e4e154109a 100644 --- a/packages/backend/src/core/entities/RenoteMutingEntityService.ts +++ b/packages/backend/src/core/entities/RenoteMutingEntityService.ts @@ -30,6 +30,9 @@ export class RenoteMutingEntityService { public async pack( src: MiRenoteMuting['id'] | MiRenoteMuting, me?: { id: MiUser['id'] } | null | undefined, + hints?: { + packedMutee?: Packed<'UserDetailedNotMe'> + }, ): Promise> { const muting = typeof src === 'object' ? src : await this.renoteMutingsRepository.findOneByOrFail({ id: src }); @@ -37,18 +40,21 @@ export class RenoteMutingEntityService { id: muting.id, createdAt: this.idService.parse(muting.id).date.toISOString(), muteeId: muting.muteeId, - mutee: this.userEntityService.pack(muting.muteeId, me, { + mutee: hints?.packedMutee ?? this.userEntityService.pack(muting.muteeId, me, { schema: 'UserDetailedNotMe', }), }); } @bindThis - public packMany( - mutings: any[], + public async packMany( + mutings: MiRenoteMuting[], me: { id: MiUser['id'] }, ) { - return Promise.all(mutings.map(x => this.pack(x, me))); + const _users = mutings.map(({ mutee, muteeId }) => mutee ?? muteeId); + const _userMap = await this.userEntityService.packMany(_users, me, { schema: 'UserDetailedNotMe' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all(mutings.map(muting => this.pack(muting, me, { packedMutee: _userMap.get(muting.muteeId) }))); } } diff --git a/packages/backend/src/core/entities/ReversiGameEntityService.ts b/packages/backend/src/core/entities/ReversiGameEntityService.ts index 32cbe631e4..df042e75c1 100644 --- a/packages/backend/src/core/entities/ReversiGameEntityService.ts +++ b/packages/backend/src/core/entities/ReversiGameEntityService.ts @@ -28,13 +28,15 @@ export class ReversiGameEntityService { @bindThis public async packDetail( src: MiReversiGame['id'] | MiReversiGame, + hint?: { + packedUser1?: Packed<'UserLite'>, + packedUser2?: Packed<'UserLite'>, + }, ): Promise> { const game = typeof src === 'object' ? src : await this.reversiGamesRepository.findOneByOrFail({ id: src }); - const users = await Promise.all([ - this.userEntityService.pack(game.user1 ?? game.user1Id), - this.userEntityService.pack(game.user2 ?? game.user2Id), - ]); + const user1 = hint?.packedUser1 ?? await this.userEntityService.pack(game.user1 ?? game.user1Id); + const user2 = hint?.packedUser2 ?? await this.userEntityService.pack(game.user2 ?? game.user2Id); return await awaitAll({ id: game.id, @@ -49,10 +51,10 @@ export class ReversiGameEntityService { user2Ready: game.user2Ready, user1Id: game.user1Id, user2Id: game.user2Id, - user1: users[0], - user2: users[1], + user1, + user2, winnerId: game.winnerId, - winner: game.winnerId ? users.find(u => u.id === game.winnerId)! : null, + winner: game.winnerId ? [user1, user2].find(u => u.id === game.winnerId)! : null, surrenderedUserId: game.surrenderedUserId, timeoutUserId: game.timeoutUserId, black: game.black, @@ -68,22 +70,35 @@ export class ReversiGameEntityService { } @bindThis - public packDetailMany( - xs: MiReversiGame[], + public async packDetailMany( + games: MiReversiGame[], ) { - return Promise.all(xs.map(x => this.packDetail(x))); + const _user1s = games.map(({ user1, user1Id }) => user1 ?? user1Id); + const _user2s = games.map(({ user2, user2Id }) => user2 ?? user2Id); + const _userMap = await this.userEntityService.packMany([..._user1s, ..._user2s]) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + games.map(game => { + return this.packDetail(game, { + packedUser1: _userMap.get(game.user1Id), + packedUser2: _userMap.get(game.user2Id), + }); + }), + ); } @bindThis public async packLite( src: MiReversiGame['id'] | MiReversiGame, + hint?: { + packedUser1?: Packed<'UserLite'>, + packedUser2?: Packed<'UserLite'>, + }, ): Promise> { const game = typeof src === 'object' ? src : await this.reversiGamesRepository.findOneByOrFail({ id: src }); - const users = await Promise.all([ - this.userEntityService.pack(game.user1 ?? game.user1Id), - this.userEntityService.pack(game.user2 ?? game.user2Id), - ]); + const user1 = hint?.packedUser1 ?? await this.userEntityService.pack(game.user1 ?? game.user1Id); + const user2 = hint?.packedUser2 ?? await this.userEntityService.pack(game.user2 ?? game.user2Id); return await awaitAll({ id: game.id, @@ -94,10 +109,10 @@ export class ReversiGameEntityService { isEnded: game.isEnded, user1Id: game.user1Id, user2Id: game.user2Id, - user1: users[0], - user2: users[1], + user1, + user2, winnerId: game.winnerId, - winner: game.winnerId ? users.find(u => u.id === game.winnerId)! : null, + winner: game.winnerId ? [user1, user2].find(u => u.id === game.winnerId)! : null, surrenderedUserId: game.surrenderedUserId, timeoutUserId: game.timeoutUserId, black: game.black, @@ -111,10 +126,21 @@ export class ReversiGameEntityService { } @bindThis - public packLiteMany( - xs: MiReversiGame[], + public async packLiteMany( + games: MiReversiGame[], ) { - return Promise.all(xs.map(x => this.packLite(x))); + const _user1s = games.map(({ user1, user1Id }) => user1 ?? user1Id); + const _user2s = games.map(({ user2, user2Id }) => user2 ?? user2Id); + const _userMap = await this.userEntityService.packMany([..._user1s, ..._user2s]) + .then(users => new Map(users.map(u => [u.id, u]))); + return Promise.all( + games.map(game => { + return this.packLite(game, { + packedUser1: _userMap.get(game.user1Id), + packedUser2: _userMap.get(game.user2Id), + }); + }), + ); } } diff --git a/packages/backend/src/core/entities/UserEntityService.ts b/packages/backend/src/core/entities/UserEntityService.ts index 8f5d986fac..9e234318b5 100644 --- a/packages/backend/src/core/entities/UserEntityService.ts +++ b/packages/backend/src/core/entities/UserEntityService.ts @@ -7,6 +7,7 @@ import { Inject, Injectable } from '@nestjs/common'; import * as Redis from 'ioredis'; import _Ajv from 'ajv'; import { ModuleRef } from '@nestjs/core'; +import { In } from 'typeorm'; import { DI } from '@/di-symbols.js'; import type { Config } from '@/config.js'; import type { Packed } from '@/misc/json-schema.js'; @@ -14,9 +15,32 @@ import type { Promiseable } from '@/misc/prelude/await-all.js'; import { awaitAll } from '@/misc/prelude/await-all.js'; import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from '@/const.js'; import type { MiLocalUser, MiPartialLocalUser, MiPartialRemoteUser, MiRemoteUser, MiUser } from '@/models/User.js'; -import { birthdaySchema, listenbrainzSchema, descriptionSchema, localUsernameSchema, locationSchema, nameSchema, passwordSchema } from '@/models/User.js'; -import { MiNotification } from '@/models/Notification.js'; -import type { UsersRepository, UserSecurityKeysRepository, FollowingsRepository, FollowRequestsRepository, BlockingsRepository, MutingsRepository, DriveFilesRepository, NoteUnreadsRepository, UserNotePiningsRepository, UserProfilesRepository, AnnouncementReadsRepository, AnnouncementsRepository, MiUserProfile, RenoteMutingsRepository, UserMemoRepository } from '@/models/_.js'; +import { + birthdaySchema, + descriptionSchema, + listenbrainzSchema, + localUsernameSchema, + locationSchema, + nameSchema, + passwordSchema, +} from '@/models/User.js'; +import type { + BlockingsRepository, + DriveFilesRepository, + FollowingsRepository, + FollowRequestsRepository, + MiFollowing, + MiUserNotePining, + MiUserProfile, + MutingsRepository, + NoteUnreadsRepository, + RenoteMutingsRepository, + UserMemoRepository, + UserNotePiningsRepository, + UserProfilesRepository, + UserSecurityKeysRepository, + UsersRepository, +} from '@/models/_.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js'; @@ -46,6 +70,19 @@ function isRemoteUser(user: MiUser | { host: MiUser['host'] }): boolean { return !isLocalUser(user); } +export type UserRelation = { + id: MiUser['id'] + following: MiFollowing | null, + isFollowing: boolean + isFollowed: boolean + hasPendingFollowRequestFromYou: boolean + hasPendingFollowRequestToYou: boolean + isBlocking: boolean + isBlocked: boolean + isMuted: boolean + isRenoteMuted: boolean +} + @Injectable() export class UserEntityService implements OnModuleInit { private apPersonService: ApPersonService; @@ -101,12 +138,6 @@ export class UserEntityService implements OnModuleInit { @Inject(DI.userProfilesRepository) private userProfilesRepository: UserProfilesRepository, - @Inject(DI.announcementReadsRepository) - private announcementReadsRepository: AnnouncementReadsRepository, - - @Inject(DI.announcementsRepository) - private announcementsRepository: AnnouncementsRepository, - @Inject(DI.userMemosRepository) private userMemosRepository: UserMemoRepository, ) { @@ -139,7 +170,7 @@ export class UserEntityService implements OnModuleInit { public isRemoteUser = isRemoteUser; @bindThis - public async getRelation(me: MiUser['id'], target: MiUser['id']) { + public async getRelation(me: MiUser['id'], target: MiUser['id']): Promise { const [ following, isFollowed, @@ -212,6 +243,80 @@ export class UserEntityService implements OnModuleInit { }; } + @bindThis + public async getRelations(me: MiUser['id'], targets: MiUser['id'][]): Promise> { + const [ + followers, + followees, + followersRequests, + followeesRequests, + blockers, + blockees, + muters, + renoteMuters, + ] = await Promise.all([ + this.followingsRepository.findBy({ followerId: me }) + .then(f => new Map(f.map(it => [it.followeeId, it]))), + this.followingsRepository.createQueryBuilder('f') + .select('f.followerId') + .where('f.followeeId = :me', { me }) + .getRawMany<{ f_followerId: string }>() + .then(it => it.map(it => it.f_followerId)), + this.followRequestsRepository.createQueryBuilder('f') + .select('f.followeeId') + .where('f.followerId = :me', { me }) + .getRawMany<{ f_followeeId: string }>() + .then(it => it.map(it => it.f_followeeId)), + this.followRequestsRepository.createQueryBuilder('f') + .select('f.followerId') + .where('f.followeeId = :me', { me }) + .getRawMany<{ f_followerId: string }>() + .then(it => it.map(it => it.f_followerId)), + this.blockingsRepository.createQueryBuilder('b') + .select('b.blockeeId') + .where('b.blockerId = :me', { me }) + .getRawMany<{ b_blockeeId: string }>() + .then(it => it.map(it => it.b_blockeeId)), + this.blockingsRepository.createQueryBuilder('b') + .select('b.blockerId') + .where('b.blockeeId = :me', { me }) + .getRawMany<{ b_blockerId: string }>() + .then(it => it.map(it => it.b_blockerId)), + this.mutingsRepository.createQueryBuilder('m') + .select('m.muteeId') + .where('m.muterId = :me', { me }) + .getRawMany<{ m_muteeId: string }>() + .then(it => it.map(it => it.m_muteeId)), + this.renoteMutingsRepository.createQueryBuilder('m') + .select('m.muteeId') + .where('m.muterId = :me', { me }) + .getRawMany<{ m_muteeId: string }>() + .then(it => it.map(it => it.m_muteeId)), + ]); + + return new Map( + targets.map(target => { + const following = followers.get(target) ?? null; + + return [ + target, + { + id: target, + following: following, + isFollowing: following != null, + isFollowed: followees.includes(target), + hasPendingFollowRequestFromYou: followersRequests.includes(target), + hasPendingFollowRequestToYou: followeesRequests.includes(target), + isBlocking: blockers.includes(target), + isBlocked: blockees.includes(target), + isMuted: muters.includes(target), + isRenoteMuted: renoteMuters.includes(target), + }, + ]; + }), + ); + } + @bindThis public async getHasUnreadAntenna(userId: MiUser['id']): Promise { /* @@ -304,6 +409,9 @@ export class UserEntityService implements OnModuleInit { schema?: S, includeSecrets?: boolean, userProfile?: MiUserProfile, + userRelations?: Map, + userMemos?: Map, + pinNotes?: Map, }, ): Promise> { const opts = Object.assign({ @@ -344,13 +452,41 @@ export class UserEntityService implements OnModuleInit { const isMe = meId === user.id; const iAmModerator = me ? await this.roleService.isModerator(me as MiUser) : false; - const relation = meId && !isMe && isDetailed ? await this.getRelation(meId, user.id) : null; - const pins = isDetailed ? await this.userNotePiningsRepository.createQueryBuilder('pin') - .where('pin.userId = :userId', { userId: user.id }) - .innerJoinAndSelect('pin.note', 'note') - .orderBy('pin.id', 'DESC') - .getMany() : []; - const profile = isDetailed ? (opts.userProfile ?? await this.userProfilesRepository.findOneByOrFail({ userId: user.id })) : null; + const profile = isDetailed + ? (opts.userProfile ?? await this.userProfilesRepository.findOneByOrFail({ userId: user.id })) + : null; + + let relation: UserRelation | null = null; + if (meId && !isMe && isDetailed) { + if (opts.userRelations) { + relation = opts.userRelations.get(user.id) ?? null; + } else { + relation = await this.getRelation(meId, user.id); + } + } + + let memo: string | null = null; + if (isDetailed && meId) { + if (opts.userMemos) { + memo = opts.userMemos.get(user.id) ?? null; + } else { + memo = await this.userMemosRepository.findOneBy({ userId: meId, targetUserId: user.id }) + .then(row => row?.memo ?? null); + } + } + + let pins: MiUserNotePining[] = []; + if (isDetailed) { + if (opts.pinNotes) { + pins = opts.pinNotes.get(user.id) ?? []; + } else { + pins = await this.userNotePiningsRepository.createQueryBuilder('pin') + .where('pin.userId = :userId', { userId: user.id }) + .innerJoinAndSelect('pin.note', 'note') + .orderBy('pin.id', 'DESC') + .getMany(); + } + } const mastoapi = !isDetailed ? opts.userProfile ?? await this.userProfilesRepository.findOneByOrFail({ userId: user.id }) : null; @@ -452,9 +588,7 @@ export class UserEntityService implements OnModuleInit { twoFactorEnabled: profile!.twoFactorEnabled, usePasswordLessLogin: profile!.usePasswordLessLogin, securityKeys: profile!.twoFactorEnabled - ? this.userSecurityKeysRepository.countBy({ - userId: user.id, - }).then(result => result >= 1) + ? this.userSecurityKeysRepository.countBy({ userId: user.id }).then(result => result >= 1) : false, roles: this.roleService.getUserRoles(user.id).then(roles => roles.filter(role => role.isPublic).sort((a, b) => b.displayOrder - a.displayOrder).map(role => ({ id: role.id, @@ -466,10 +600,7 @@ export class UserEntityService implements OnModuleInit { isAdministrator: role.isAdministrator, displayOrder: role.displayOrder, }))), - memo: meId == null ? null : await this.userMemosRepository.findOneBy({ - userId: meId, - targetUserId: user.id, - }).then(row => row?.memo ?? null), + memo: memo, moderationNote: iAmModerator ? (profile!.moderationNote ?? '') : undefined, } : {}), @@ -552,7 +683,7 @@ export class UserEntityService implements OnModuleInit { return await awaitAll(packed); } - public packMany( + public async packMany( users: (MiUser['id'] | MiUser)[], me?: { id: MiUser['id'] } | null | undefined, options?: { @@ -560,6 +691,69 @@ export class UserEntityService implements OnModuleInit { includeSecrets?: boolean, }, ): Promise[]> { - return Promise.all(users.map(u => this.pack(u, me, options))); + // -- IDのみの要素を補完して完全なエンティティ一覧を作る + + const _users = users.filter((user): user is MiUser => typeof user !== 'string'); + if (_users.length !== users.length) { + _users.push( + ...await this.usersRepository.findBy({ + id: In(users.filter((user): user is string => typeof user === 'string')), + }), + ); + } + const _userIds = _users.map(u => u.id); + + // -- 実行者の有無や指定スキーマの種別によって要否が異なる値群を取得 + + let profilesMap: Map = new Map(); + let userRelations: Map = new Map(); + let userMemos: Map = new Map(); + let pinNotes: Map = new Map(); + + if (options?.schema !== 'UserLite') { + profilesMap = await this.userProfilesRepository.findBy({ userId: In(_userIds) }) + .then(profiles => new Map(profiles.map(p => [p.userId, p]))); + + const meId = me ? me.id : null; + if (meId) { + userMemos = await this.userMemosRepository.findBy({ userId: meId }) + .then(memos => new Map(memos.map(memo => [memo.targetUserId, memo.memo]))); + + if (_userIds.length > 0) { + userRelations = await this.getRelations(meId, _userIds); + pinNotes = await this.userNotePiningsRepository.createQueryBuilder('pin') + .where('pin.userId IN (:...userIds)', { userIds: _userIds }) + .innerJoinAndSelect('pin.note', 'note') + .getMany() + .then(pinsNotes => { + const map = new Map(); + for (const note of pinsNotes) { + const notes = map.get(note.userId) ?? []; + notes.push(note); + map.set(note.userId, notes); + } + for (const [, notes] of map.entries()) { + // pack側ではDESCで取得しているので、それに合わせて降順に並び替えておく + notes.sort((a, b) => b.id.localeCompare(a.id)); + } + return map; + }); + } + } + } + + return Promise.all( + _users.map(u => this.pack( + u, + me, + { + ...options, + userProfile: profilesMap.get(u.id), + userRelations: userRelations, + userMemos: userMemos, + pinNotes: pinNotes, + }, + )), + ); } } diff --git a/packages/backend/src/core/entities/UserListEntityService.ts b/packages/backend/src/core/entities/UserListEntityService.ts index 09cab24521..b77249c5cb 100644 --- a/packages/backend/src/core/entities/UserListEntityService.ts +++ b/packages/backend/src/core/entities/UserListEntityService.ts @@ -50,11 +50,14 @@ export class UserListEntityService { public async packMembershipsMany( memberships: MiUserListMembership[], ) { + const _users = memberships.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users) + .then(users => new Map(users.map(u => [u.id, u]))); return Promise.all(memberships.map(async x => ({ id: x.id, createdAt: this.idService.parse(x.id).date.toISOString(), userId: x.userId, - user: await this.userEntityService.pack(x.userId), + user: _userMap.get(x.userId) ?? await this.userEntityService.pack(x.userId), withReplies: x.withReplies, }))); } diff --git a/packages/backend/src/misc/fastify-hook-handlers.ts b/packages/backend/src/misc/fastify-hook-handlers.ts index 49a48f6a6b..3e1c099e00 100644 --- a/packages/backend/src/misc/fastify-hook-handlers.ts +++ b/packages/backend/src/misc/fastify-hook-handlers.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import type { onRequestHookHandler } from 'fastify'; export const handleRequestRedirectToOmitSearch: onRequestHookHandler = (request, reply, done) => { diff --git a/packages/backend/src/misc/gen-identicon.ts b/packages/backend/src/misc/gen-identicon.ts index 62a8ab8ace..342e0f8602 100644 --- a/packages/backend/src/misc/gen-identicon.ts +++ b/packages/backend/src/misc/gen-identicon.ts @@ -8,9 +8,8 @@ * https://en.wikipedia.org/wiki/Identicon */ -import * as p from 'pureimage'; +import { createCanvas } from '@napi-rs/canvas'; import gen from 'random-seed'; -import type { WriteStream } from 'node:fs'; const size = 128; // px const n = 5; // resolution @@ -45,9 +44,9 @@ const sideN = Math.floor(n / 2); /** * Generate buffer of an identicon by seed */ -export function genIdenticon(seed: string, stream: WriteStream): Promise { +export async function genIdenticon(seed: string): Promise { const rand = gen.create(seed); - const canvas = p.make(size, size, undefined); + const canvas = createCanvas(size, size); const ctx = canvas.getContext('2d'); const bgColors = colors[rand(colors.length)]; @@ -101,5 +100,5 @@ export function genIdenticon(seed: string, stream: WriteStream): Promise { } } - return p.encodePNGToStream(canvas, stream); + return await canvas.encode('png'); } diff --git a/packages/backend/src/misc/is-pure-renote.ts b/packages/backend/src/misc/is-pure-renote.ts deleted file mode 100644 index 994d981522..0000000000 --- a/packages/backend/src/misc/is-pure-renote.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { MiNote } from '@/models/Note.js'; - -export function isPureRenote(note: MiNote): note is MiNote & { renoteId: NonNullable } { - if (!note.renoteId) return false; - - if (note.text) return false; // it's quoted with text - if (note.fileIds.length !== 0) return false; // it's quoted with files - if (note.hasPoll) return false; // it's quoted with poll - return true; -} diff --git a/packages/backend/src/misc/is-quote.ts b/packages/backend/src/misc/is-quote.ts deleted file mode 100644 index 75b29f63f4..0000000000 --- a/packages/backend/src/misc/is-quote.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * SPDX-FileCopyrightText: syuilo and misskey-project - * SPDX-License-Identifier: AGPL-3.0-only - */ - -import type { MiNote } from '@/models/Note.js'; - -// eslint-disable-next-line import/no-default-export -export default function(note: MiNote): boolean { - // sync with NoteCreateService.isQuote - return note.renoteId != null && (note.text != null || note.hasPoll || (note.fileIds != null && note.fileIds.length > 0)); -} diff --git a/packages/backend/src/misc/is-renote.ts b/packages/backend/src/misc/is-renote.ts new file mode 100644 index 0000000000..48f821806c --- /dev/null +++ b/packages/backend/src/misc/is-renote.ts @@ -0,0 +1,67 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import type { MiNote } from '@/models/Note.js'; +import type { Packed } from '@/misc/json-schema.js'; + +type Renote = + MiNote & { + renoteId: NonNullable + }; + +type Quote = + Renote & ({ + text: NonNullable + } | { + cw: NonNullable + } | { + replyId: NonNullable + reply: NonNullable + } | { + hasPoll: true + }); + +export function isRenote(note: MiNote): note is Renote { + return note.renoteId != null; +} + +export function isQuote(note: Renote): note is Quote { + // NOTE: SYNC WITH NoteCreateService.isQuote + return note.text != null || + note.cw != null || + note.replyId != null || + note.hasPoll || + note.fileIds.length > 0; +} + +type PackedRenote = + Packed<'Note'> & { + renoteId: NonNullable['renoteId']> + }; + +type PackedQuote = + PackedRenote & ({ + text: NonNullable['text']> + } | { + cw: NonNullable['cw']> + } | { + replyId: NonNullable['replyId']> + } | { + poll: NonNullable['poll']> + } | { + fileIds: NonNullable['fileIds']> + }); + +export function isRenotePacked(note: Packed<'Note'>): note is PackedRenote { + return note.renoteId != null; +} + +export function isQuotePacked(note: PackedRenote): note is PackedQuote { + return note.text != null || + note.cw != null || + note.replyId != null || + note.poll != null || + (note.fileIds != null && note.fileIds.length > 0); +} diff --git a/packages/backend/src/misc/json-schema.ts b/packages/backend/src/misc/json-schema.ts index 46b0bb2fab..41e5bfe9e4 100644 --- a/packages/backend/src/misc/json-schema.ts +++ b/packages/backend/src/misc/json-schema.ts @@ -48,6 +48,7 @@ import { packedRoleCondFormulaValueCreatedSchema, packedRoleCondFormulaFollowersOrFollowingOrNotesSchema, packedRoleCondFormulaValueSchema, + packedRoleCondFormulaValueUserSettingBooleanSchema, } from '@/models/json-schema/role.js'; import { packedAdSchema } from '@/models/json-schema/ad.js'; import { packedReversiGameLiteSchema, packedReversiGameDetailedSchema } from '@/models/json-schema/reversi-game.js'; @@ -97,6 +98,7 @@ export const refs = { RoleCondFormulaLogics: packedRoleCondFormulaLogicsSchema, RoleCondFormulaValueNot: packedRoleCondFormulaValueNot, RoleCondFormulaValueIsLocalOrRemote: packedRoleCondFormulaValueIsLocalOrRemoteSchema, + RoleCondFormulaValueUserSettingBooleanSchema: packedRoleCondFormulaValueUserSettingBooleanSchema, RoleCondFormulaValueAssignedRole: packedRoleCondFormulaValueAssignedRoleSchema, RoleCondFormulaValueCreated: packedRoleCondFormulaValueCreatedSchema, RoleCondFormulaFollowersOrFollowingOrNotes: packedRoleCondFormulaFollowersOrFollowingOrNotesSchema, @@ -226,7 +228,7 @@ export type SchemaTypeDef

= p['items']['allOf'] extends ReadonlyArray ? UnionToIntersection>>[] : never ) : - p['items'] extends NonNullable ? SchemaTypeDef[] : + p['items'] extends NonNullable ? SchemaType[] : any[] ) : p['anyOf'] extends ReadonlyArray ? UnionSchemaType & PartialIntersection> : diff --git a/packages/backend/src/misc/loader.ts b/packages/backend/src/misc/loader.ts index 25f7b54d31..7f29b9db10 100644 --- a/packages/backend/src/misc/loader.ts +++ b/packages/backend/src/misc/loader.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export type FetchFunction = (key: K) => Promise; type ResolveReject = Parameters>[0]>; diff --git a/packages/backend/src/models/Antenna.ts b/packages/backend/src/models/Antenna.ts index 332a899768..33e6f48189 100644 --- a/packages/backend/src/models/Antenna.ts +++ b/packages/backend/src/models/Antenna.ts @@ -72,6 +72,11 @@ export class MiAntenna { }) public caseSensitive: boolean; + @Column('boolean', { + default: false, + }) + public excludeBots: boolean; + @Column('boolean', { default: false, }) @@ -85,9 +90,6 @@ export class MiAntenna { }) public expression: string | null; - @Column('boolean') - public notify: boolean; - @Index() @Column('boolean', { default: true, diff --git a/packages/backend/src/models/Instance.ts b/packages/backend/src/models/Instance.ts index 7dd4e5b10c..dd625f95d3 100644 --- a/packages/backend/src/models/Instance.ts +++ b/packages/backend/src/models/Instance.ts @@ -81,13 +81,22 @@ export class MiInstance { public isNotResponding: boolean; /** - * このインスタンスへの配信を停止するか + * このインスタンスと不通になった日時 + */ + @Column('timestamp with time zone', { + nullable: true, + }) + public notRespondingSince: Date | null; + + /** + * このインスタンスへの配信状態 */ @Index() - @Column('boolean', { - default: false, + @Column('enum', { + default: 'none', + enum: ['none', 'manuallySuspended', 'goneSuspended', 'autoSuspendedForNotResponding'], }) - public isSuspended: boolean; + public suspensionState: 'none' | 'manuallySuspended' | 'goneSuspended' | 'autoSuspendedForNotResponding'; @Column('varchar', { length: 64, nullable: true, diff --git a/packages/backend/src/models/Meta.ts b/packages/backend/src/models/Meta.ts index dd2e78cde2..fb021f0f6b 100644 --- a/packages/backend/src/models/Meta.ts +++ b/packages/backend/src/models/Meta.ts @@ -287,12 +287,6 @@ export class MiMeta { }) public enableBotTrending: boolean; - @Column('varchar', { - length: 1024, - nullable: true, - }) - public summalyProxy: string | null; - @Column('boolean', { default: false, }) @@ -409,6 +403,12 @@ export class MiMeta { }) public donationUrl: string | null; + @Column('varchar', { + length: 1024, + nullable: true, + }) + public inquiryUrl: string | null; + @Column('varchar', { length: 8192, nullable: true, @@ -631,4 +631,36 @@ export class MiMeta { length: 256, array: true, default: '{}', }) public bubbleInstances: string[]; + + @Column('boolean', { + default: true, + }) + public urlPreviewEnabled: boolean; + + @Column('integer', { + default: 10000, + }) + public urlPreviewTimeout: number; + + @Column('bigint', { + default: 1024 * 1024 * 10, + }) + public urlPreviewMaximumContentLength: number; + + @Column('boolean', { + default: true, + }) + public urlPreviewRequireContentLength: boolean; + + @Column('varchar', { + length: 1024, + nullable: true, + }) + public urlPreviewSummaryProxyUrl: string | null; + + @Column('varchar', { + length: 1024, + nullable: true, + }) + public urlPreviewUserAgent: string | null; } diff --git a/packages/backend/src/models/NoteEdit.ts b/packages/backend/src/models/NoteEdit.ts index 9ec989dd50..cfd9ad748e 100644 --- a/packages/backend/src/models/NoteEdit.ts +++ b/packages/backend/src/models/NoteEdit.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Entity, JoinColumn, Column, ManyToOne, PrimaryColumn, Index } from "typeorm"; import { id } from './util/id.js'; import { MiNote } from './Note.js'; diff --git a/packages/backend/src/models/Poll.ts b/packages/backend/src/models/Poll.ts index c2693dbb19..ca985c8b24 100644 --- a/packages/backend/src/models/Poll.ts +++ b/packages/backend/src/models/Poll.ts @@ -8,6 +8,7 @@ import { noteVisibilities } from '@/types.js'; import { id } from './util/id.js'; import { MiNote } from './Note.js'; import type { MiUser } from './User.js'; +import type { MiChannel } from "@/models/Channel.js"; @Entity('poll') export class MiPoll { @@ -58,6 +59,14 @@ export class MiPoll { comment: '[Denormalized]', }) public userHost: string | null; + + @Index() + @Column({ + ...id(), + nullable: true, + comment: '[Denormalized]', + }) + public channelId: MiChannel['id'] | null; //#endregion constructor(data: Partial) { diff --git a/packages/backend/src/models/ReversiGame.ts b/packages/backend/src/models/ReversiGame.ts index c03335dd63..6b29a0ce8c 100644 --- a/packages/backend/src/models/ReversiGame.ts +++ b/packages/backend/src/models/ReversiGame.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { PrimaryColumn, Entity, Index, JoinColumn, Column, ManyToOne } from 'typeorm'; import { id } from './util/id.js'; import { MiUser } from './User.js'; diff --git a/packages/backend/src/models/Role.ts b/packages/backend/src/models/Role.ts index 058abe3118..a173971b2c 100644 --- a/packages/backend/src/models/Role.ts +++ b/packages/backend/src/models/Role.ts @@ -6,69 +6,149 @@ import { Entity, Column, PrimaryColumn } from 'typeorm'; import { id } from './util/id.js'; +/** + * ~かつ~ + * 複数の条件を同時に満たす場合のみ成立とする + */ type CondFormulaValueAnd = { type: 'and'; values: RoleCondFormulaValue[]; }; +/** + * ~または~ + * 複数の条件のうち、いずれかを満たす場合のみ成立とする + */ type CondFormulaValueOr = { type: 'or'; values: RoleCondFormulaValue[]; }; +/** + * ~ではない + * 条件を満たさない場合のみ成立とする + */ type CondFormulaValueNot = { type: 'not'; value: RoleCondFormulaValue; }; +/** + * ローカルユーザーのみ成立とする + */ type CondFormulaValueIsLocal = { type: 'isLocal'; }; +/** + * リモートユーザーのみ成立とする + */ type CondFormulaValueIsRemote = { type: 'isRemote'; }; +/** + * 既に指定のマニュアルロールにアサインされている場合のみ成立とする + */ type CondFormulaValueRoleAssignedTo = { type: 'roleAssignedTo'; roleId: string; }; +/** + * サスペンド済みアカウントの場合のみ成立とする + */ +type CondFormulaValueIsSuspended = { + type: 'isSuspended'; +}; + +/** + * 鍵アカウントの場合のみ成立とする + */ +type CondFormulaValueIsLocked = { + type: 'isLocked'; +}; + +/** + * botアカウントの場合のみ成立とする + */ +type CondFormulaValueIsBot = { + type: 'isBot'; +}; + +/** + * 猫アカウントの場合のみ成立とする + */ +type CondFormulaValueIsCat = { + type: 'isCat'; +}; + +/** + * 「ユーザを見つけやすくする」が有効なアカウントの場合のみ成立とする + */ +type CondFormulaValueIsExplorable = { + type: 'isExplorable'; +}; + +/** + * ユーザが作成されてから指定期間経過した場合のみ成立とする + */ type CondFormulaValueCreatedLessThan = { type: 'createdLessThan'; sec: number; }; +/** + * ユーザが作成されてから指定期間経っていない場合のみ成立とする + */ type CondFormulaValueCreatedMoreThan = { type: 'createdMoreThan'; sec: number; }; +/** + * フォロワー数が指定値以下の場合のみ成立とする + */ type CondFormulaValueFollowersLessThanOrEq = { type: 'followersLessThanOrEq'; value: number; }; +/** + * フォロワー数が指定値以上の場合のみ成立とする + */ type CondFormulaValueFollowersMoreThanOrEq = { type: 'followersMoreThanOrEq'; value: number; }; +/** + * フォロー数が指定値以下の場合のみ成立とする + */ type CondFormulaValueFollowingLessThanOrEq = { type: 'followingLessThanOrEq'; value: number; }; +/** + * フォロー数が指定値以上の場合のみ成立とする + */ type CondFormulaValueFollowingMoreThanOrEq = { type: 'followingMoreThanOrEq'; value: number; }; +/** + * 投稿数が指定値以下の場合のみ成立とする + */ type CondFormulaValueNotesLessThanOrEq = { type: 'notesLessThanOrEq'; value: number; }; +/** + * 投稿数が指定値以上の場合のみ成立とする + */ type CondFormulaValueNotesMoreThanOrEq = { type: 'notesMoreThanOrEq'; value: number; @@ -80,6 +160,11 @@ export type RoleCondFormulaValue = { id: string } & ( CondFormulaValueNot | CondFormulaValueIsLocal | CondFormulaValueIsRemote | + CondFormulaValueIsSuspended | + CondFormulaValueIsLocked | + CondFormulaValueIsBot | + CondFormulaValueIsCat | + CondFormulaValueIsExplorable | CondFormulaValueRoleAssignedTo | CondFormulaValueCreatedLessThan | CondFormulaValueCreatedMoreThan | diff --git a/packages/backend/src/models/json-schema/antenna.ts b/packages/backend/src/models/json-schema/antenna.ts index 74622b6193..b5b9a5b42c 100644 --- a/packages/backend/src/models/json-schema/antenna.ts +++ b/packages/backend/src/models/json-schema/antenna.ts @@ -72,9 +72,10 @@ export const packedAntennaSchema = { optional: false, nullable: false, default: false, }, - notify: { + excludeBots: { type: 'boolean', optional: false, nullable: false, + default: false, }, withReplies: { type: 'boolean', @@ -94,5 +95,10 @@ export const packedAntennaSchema = { optional: false, nullable: false, default: false, }, + notify: { + type: 'boolean', + optional: false, nullable: false, + default: false, + }, }, } as const; diff --git a/packages/backend/src/models/json-schema/clip.ts b/packages/backend/src/models/json-schema/clip.ts index ca4886c978..c4e7055cd8 100644 --- a/packages/backend/src/models/json-schema/clip.ts +++ b/packages/backend/src/models/json-schema/clip.ts @@ -52,5 +52,9 @@ export const packedClipSchema = { type: 'boolean', optional: true, nullable: false, }, + notesCount: { + type: 'integer', + optional: true, nullable: false, + }, }, } as const; diff --git a/packages/backend/src/models/json-schema/federation-instance.ts b/packages/backend/src/models/json-schema/federation-instance.ts index 7b8ab22831..a602126dc8 100644 --- a/packages/backend/src/models/json-schema/federation-instance.ts +++ b/packages/backend/src/models/json-schema/federation-instance.ts @@ -45,6 +45,11 @@ export const packedFederationInstanceSchema = { type: 'boolean', optional: false, nullable: false, }, + suspensionState: { + type: 'string', + nullable: false, optional: false, + enum: ['none', 'manuallySuspended', 'goneSuspended', 'autoSuspendedForNotResponding'], + }, isBlocked: { type: 'boolean', optional: false, nullable: false, diff --git a/packages/backend/src/models/json-schema/meta.ts b/packages/backend/src/models/json-schema/meta.ts index 9db3f7f809..7edd877f80 100644 --- a/packages/backend/src/models/json-schema/meta.ts +++ b/packages/backend/src/models/json-schema/meta.ts @@ -223,6 +223,10 @@ export const packedMetaLiteSchema = { type: 'string', optional: false, nullable: false, }, + enableUrlPreview: { + type: 'boolean', + optional: false, nullable: false, + }, backgroundImageUrl: { type: 'string', optional: false, nullable: true, @@ -239,6 +243,10 @@ export const packedMetaLiteSchema = { type: 'string', optional: false, nullable: true, }, + inquiryUrl: { + type: 'string', + optional: false, nullable: true, + }, serverRules: { type: 'array', optional: false, nullable: false, diff --git a/packages/backend/src/models/json-schema/note-edit.ts b/packages/backend/src/models/json-schema/note-edit.ts index a58e2aa1de..ba936f866b 100644 --- a/packages/backend/src/models/json-schema/note-edit.ts +++ b/packages/backend/src/models/json-schema/note-edit.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + export const packedNoteEdit = { type: "object", properties: { diff --git a/packages/backend/src/models/json-schema/note.ts b/packages/backend/src/models/json-schema/note.ts index bb4ccc7ee4..2641161c8b 100644 --- a/packages/backend/src/models/json-schema/note.ts +++ b/packages/backend/src/models/json-schema/note.ts @@ -223,6 +223,10 @@ export const packedNoteSchema = { }], }, }, + reactionCount: { + type: 'number', + optional: false, nullable: false, + }, renoteCount: { type: 'number', optional: false, nullable: false, diff --git a/packages/backend/src/models/json-schema/role.ts b/packages/backend/src/models/json-schema/role.ts index 7eba1d5443..08580d22de 100644 --- a/packages/backend/src/models/json-schema/role.ts +++ b/packages/backend/src/models/json-schema/role.ts @@ -57,6 +57,20 @@ export const packedRoleCondFormulaValueIsLocalOrRemoteSchema = { }, } as const; +export const packedRoleCondFormulaValueUserSettingBooleanSchema = { + type: 'object', + properties: { + id: { + type: 'string', optional: false, + }, + type: { + type: 'string', + nullable: false, optional: false, + enum: ['isSuspended', 'isLocked', 'isBot', 'isCat', 'isExplorable'], + }, + }, +} as const; + export const packedRoleCondFormulaValueAssignedRoleSchema = { type: 'object', properties: { @@ -135,6 +149,9 @@ export const packedRoleCondFormulaValueSchema = { { ref: 'RoleCondFormulaValueIsLocalOrRemote', }, + { + ref: 'RoleCondFormulaValueUserSettingBooleanSchema', + }, { ref: 'RoleCondFormulaValueAssignedRole', }, diff --git a/packages/backend/src/models/json-schema/signin.ts b/packages/backend/src/models/json-schema/signin.ts index d27d2490c5..45732a742b 100644 --- a/packages/backend/src/models/json-schema/signin.ts +++ b/packages/backend/src/models/json-schema/signin.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + export const packedSigninSchema = { type: 'object', properties: { diff --git a/packages/backend/src/queue/processors/CleanRemoteFilesProcessorService.ts b/packages/backend/src/queue/processors/CleanRemoteFilesProcessorService.ts index 4fa414b0b5..81842b221f 100644 --- a/packages/backend/src/queue/processors/CleanRemoteFilesProcessorService.ts +++ b/packages/backend/src/queue/processors/CleanRemoteFilesProcessorService.ts @@ -73,7 +73,6 @@ export class CleanRemoteFilesProcessorService { }); await job.updateProgress(100 / total * deletedCount); - } this.logger.succ(`All cached remote files processed. Total deleted: ${deletedCount}, Failed: ${errorCount}.`); diff --git a/packages/backend/src/queue/processors/DeliverProcessorService.ts b/packages/backend/src/queue/processors/DeliverProcessorService.ts index 5fed070929..b73195afc3 100644 --- a/packages/backend/src/queue/processors/DeliverProcessorService.ts +++ b/packages/backend/src/queue/processors/DeliverProcessorService.ts @@ -5,6 +5,7 @@ import { Inject, Injectable } from '@nestjs/common'; import * as Bull from 'bullmq'; +import { Not } from 'typeorm'; import { DI } from '@/di-symbols.js'; import type { InstancesRepository } from '@/models/_.js'; import type Logger from '@/logger.js'; @@ -62,7 +63,7 @@ export class DeliverProcessorService { if (suspendedHosts == null) { suspendedHosts = await this.instancesRepository.find({ where: { - isSuspended: true, + suspensionState: Not('none'), }, }); this.suspendedHostsCache.set(suspendedHosts); @@ -79,6 +80,7 @@ export class DeliverProcessorService { if (i.isNotResponding) { this.federatedInstanceService.update(i.id, { isNotResponding: false, + notRespondingSince: null, }); } @@ -98,7 +100,15 @@ export class DeliverProcessorService { if (!i.isNotResponding) { this.federatedInstanceService.update(i.id, { isNotResponding: true, + notRespondingSince: new Date(), }); + } else if (i.notRespondingSince) { + // 1週間以上不通ならサスペンド + if (i.suspensionState === 'none' && i.notRespondingSince.getTime() <= Date.now() - 1000 * 60 * 60 * 24 * 7) { + this.federatedInstanceService.update(i.id, { + suspensionState: 'autoSuspendedForNotResponding', + }); + } } this.apRequestChart.deliverFail(); @@ -116,7 +126,7 @@ export class DeliverProcessorService { if (job.data.isSharedInbox && res.statusCode === 410) { this.federatedInstanceService.fetch(host).then(i => { this.federatedInstanceService.update(i.id, { - isSuspended: true, + suspensionState: 'goneSuspended', }); }); throw new Bull.UnrecoverableError(`${host} is gone`); diff --git a/packages/backend/src/queue/processors/ExportAccountDataProcessorService.ts b/packages/backend/src/queue/processors/ExportAccountDataProcessorService.ts index f6a4e8e2ec..33a2362c4a 100644 --- a/packages/backend/src/queue/processors/ExportAccountDataProcessorService.ts +++ b/packages/backend/src/queue/processors/ExportAccountDataProcessorService.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import * as fs from 'node:fs'; import { Inject, Injectable } from '@nestjs/common'; import { In, IsNull, MoreThan, Not } from 'typeorm'; @@ -287,7 +292,7 @@ export class ExportAccountDataProcessorService { const mutings = await this.mutingsRepository.findBy({ muterId: user.id, }); - + while (true) { const followings = await this.followingsRepository.find({ where: { @@ -353,7 +358,7 @@ export class ExportAccountDataProcessorService { let followersCursor: MiFollowing['id'] | null = null; let exportedFollowersCount = 0; - + while (true) { const followers = await this.followingsRepository.find({ where: { @@ -680,7 +685,6 @@ export class ExportAccountDataProcessorService { localOnly: antenna.localOnly, withReplies: antenna.withReplies, withFile: antenna.withFile, - notify: antenna.notify, })); if (antennas.length - 1 !== index) { @@ -749,9 +753,9 @@ export class ExportAccountDataProcessorService { cleanup(); archiveCleanup(); if (profile.email) { - this.emailService.sendEmail(profile.email, - 'Your data archive is ready', - `Click the following link to download the archive: ${driveFile.url}
It is also available in your drive.`, + this.emailService.sendEmail(profile.email, + 'Your data archive is ready', + `Click the following link to download the archive: ${driveFile.url}
It is also available in your drive.`, `Click the following link to download the archive: ${driveFile.url}\r\n\r\nIt is also available in your drive.`, ); } diff --git a/packages/backend/src/queue/processors/ExportAntennasProcessorService.ts b/packages/backend/src/queue/processors/ExportAntennasProcessorService.ts index af48bad417..88c4ea29c0 100644 --- a/packages/backend/src/queue/processors/ExportAntennasProcessorService.ts +++ b/packages/backend/src/queue/processors/ExportAntennasProcessorService.ts @@ -81,9 +81,9 @@ export class ExportAntennasProcessorService { }) : null, caseSensitive: antenna.caseSensitive, localOnly: antenna.localOnly, + excludeBots: antenna.excludeBots, withReplies: antenna.withReplies, withFile: antenna.withFile, - notify: antenna.notify, })); if (antennas.length - 1 !== index) { write(', '); diff --git a/packages/backend/src/queue/processors/ImportAntennasProcessorService.ts b/packages/backend/src/queue/processors/ImportAntennasProcessorService.ts index 951b560597..e5b7c5ac52 100644 --- a/packages/backend/src/queue/processors/ImportAntennasProcessorService.ts +++ b/packages/backend/src/queue/processors/ImportAntennasProcessorService.ts @@ -44,11 +44,11 @@ const validate = new Ajv().compile({ } }, caseSensitive: { type: 'boolean' }, localOnly: { type: 'boolean' }, + excludeBots: { type: 'boolean' }, withReplies: { type: 'boolean' }, withFile: { type: 'boolean' }, - notify: { type: 'boolean' }, }, - required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'], + required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile'], }); @Injectable() @@ -88,9 +88,9 @@ export class ImportAntennasProcessorService { users: (antenna.src === 'list' && antenna.userListAccts !== null ? antenna.userListAccts : antenna.users).filter(Boolean), caseSensitive: antenna.caseSensitive, localOnly: antenna.localOnly, + excludeBots: antenna.excludeBots, withReplies: antenna.withReplies, withFile: antenna.withFile, - notify: antenna.notify, }).then(x => this.antennasRepository.findOneByOrFail(x.identifiers[0])); this.logger.succ('Antenna created: ' + result.id); this.globalEventService.publishInternalEvent('antennaCreated', result); diff --git a/packages/backend/src/queue/processors/ImportNotesProcessorService.ts b/packages/backend/src/queue/processors/ImportNotesProcessorService.ts index 58a0ea10ad..f89dc46722 100644 --- a/packages/backend/src/queue/processors/ImportNotesProcessorService.ts +++ b/packages/backend/src/queue/processors/ImportNotesProcessorService.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import * as fs from 'node:fs'; import * as fsp from 'node:fs/promises'; import * as crypto from 'node:crypto'; diff --git a/packages/backend/src/queue/processors/InboxProcessorService.ts b/packages/backend/src/queue/processors/InboxProcessorService.ts index 2b5b7c5619..641b8b8607 100644 --- a/packages/backend/src/queue/processors/InboxProcessorService.ts +++ b/packages/backend/src/queue/processors/InboxProcessorService.ts @@ -22,7 +22,7 @@ import { ApDbResolverService } from '@/core/activitypub/ApDbResolverService.js'; import { StatusError } from '@/misc/status-error.js'; import { UtilityService } from '@/core/UtilityService.js'; import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js'; -import { LdSignatureService } from '@/core/activitypub/LdSignatureService.js'; +import { JsonLdService } from '@/core/activitypub/JsonLdService.js'; import { ApInboxService } from '@/core/activitypub/ApInboxService.js'; import { bindThis } from '@/decorators.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; @@ -39,7 +39,7 @@ export class InboxProcessorService { private apInboxService: ApInboxService, private federatedInstanceService: FederatedInstanceService, private fetchInstanceMetadataService: FetchInstanceMetadataService, - private ldSignatureService: LdSignatureService, + private jsonLdService: JsonLdService, private apPersonService: ApPersonService, private apDbResolverService: ApDbResolverService, private instanceChart: InstanceChart, @@ -111,7 +111,7 @@ export class InboxProcessorService { // また、signatureのsignerは、activity.actorと一致する必要がある if (!httpSignatureValidated || authUser.user.uri !== activity.actor) { let renewKeyFailed = true; - + if (!httpSignatureValidated) { authUser.key = await this.apDbResolverService.refetchPublicKeyForApId(authUser.user); @@ -122,20 +122,21 @@ export class InboxProcessorService { } // 一致しなくても、でもLD-Signatureがありそうならそっちも見る - if (activity.signature && renewKeyFailed) { - if (activity.signature.type !== 'RsaSignature2017') { - throw new Bull.UnrecoverableError(`skip: unsupported LD-signature type ${activity.signature.type}`); + const ldSignature = activity.signature; + if (ldSignature) { + if (ldSignature.type !== 'RsaSignature2017') { + throw new Bull.UnrecoverableError(`skip: unsupported LD-signature type ${ldSignature.type}`); } - // activity.signature.creator: https://example.oom/users/user#main-key + // ldSignature.creator: https://example.oom/users/user#main-key // みたいになっててUserを引っ張れば公開キーも入ることを期待する - if (activity.signature.creator) { - const candicate = activity.signature.creator.replace(/#.*/, ''); + if (ldSignature.creator) { + const candicate = ldSignature.creator.replace(/#.*/, ''); await this.apPersonService.resolvePerson(candicate).catch(() => null); } // keyIdからLD-Signatureのユーザーを取得 - authUser = await this.apDbResolverService.getAuthUserFromKeyId(activity.signature.creator); + authUser = await this.apDbResolverService.getAuthUserFromKeyId(ldSignature.creator); if (authUser == null) { throw new Bull.UnrecoverableError('skip: LD-Signatureのユーザーが取得できませんでした'); } @@ -144,9 +145,10 @@ export class InboxProcessorService { throw new Bull.UnrecoverableError('skip: LD-SignatureのユーザーはpublicKeyを持っていませんでした'); } + const jsonLd = this.jsonLdService.use(); + // LD-Signature検証 - const ldSignature = this.ldSignatureService.use(); - const verified = await ldSignature.verifyRsaSignature2017(activity, authUser.key.keyPem).catch(() => false); + const verified = await jsonLd.verifyRsaSignature2017(activity, authUser.key.keyPem).catch(() => false); if (!verified) { throw new Bull.UnrecoverableError('skip: LD-Signatureの検証に失敗しました'); } @@ -154,7 +156,7 @@ export class InboxProcessorService { // アクティビティを正規化 delete activity.signature; try { - activity = await ldSignature.compact(activity) as IActivity; + activity = await jsonLd.compact(activity) as IActivity; } catch (e) { throw new Bull.UnrecoverableError(`skip: failed to compact activity: ${e}`); } @@ -191,6 +193,8 @@ export class InboxProcessorService { this.federatedInstanceService.update(i.id, { latestRequestReceivedAt: new Date(), isNotResponding: false, + // もしサーバーが死んでるために配信が止まっていた場合には自動的に復活させてあげる + suspensionState: i.suspensionState === 'autoSuspendedForNotResponding' ? 'none' : undefined, }); this.fetchInstanceMetadataService.fetchInstanceMetadata(i); @@ -205,13 +209,22 @@ export class InboxProcessorService { // アクティビティを処理 try { - await this.apInboxService.performActivity(authUser.user, activity); + const result = await this.apInboxService.performActivity(authUser.user, activity); + if (result && !result.startsWith('ok')) { + this.logger.warn(`inbox activity ignored (maybe): id=${activity.id} reason=${result}`); + return result; + } } catch (e) { if (e instanceof IdentifiableError) { if (e.id === '689ee33f-f97c-479a-ac49-1b9f8140af99') { return 'blocked notes with prohibited words'; } - if (e.id === '85ab9bd7-3a41-4530-959d-f07073900109') return 'actor has been suspended'; + if (e.id === '85ab9bd7-3a41-4530-959d-f07073900109') { + return 'actor has been suspended'; + } + if (e.id === 'd450b8a9-48e4-4dab-ae36-f4db763fda7c') { // invalid Note + return e.message; + } } throw e; } diff --git a/packages/backend/src/server/ActivityPubServerService.ts b/packages/backend/src/server/ActivityPubServerService.ts index 64bce07a98..398ad54f6a 100644 --- a/packages/backend/src/server/ActivityPubServerService.ts +++ b/packages/backend/src/server/ActivityPubServerService.ts @@ -33,7 +33,7 @@ import { UtilityService } from '@/core/UtilityService.js'; import { UserEntityService } from '@/core/entities/UserEntityService.js'; import { bindThis } from '@/decorators.js'; import { IActivity } from '@/core/activitypub/type.js'; -import { isPureRenote } from '@/misc/is-pure-renote.js'; +import { isQuote, isRenote } from '@/misc/is-renote.js'; import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions, FastifyBodyParser } from 'fastify'; import type { FindOptionsWhere } from 'typeorm'; import type Logger from '@/logger.js'; @@ -107,7 +107,7 @@ export class ActivityPubServerService { */ @bindThis private async packActivity(note: MiNote): Promise { - if (isPureRenote(note)) { + if (isRenote(note) && !isQuote(note)) { const renote = await this.notesRepository.findOneByOrFail({ id: note.renoteId }); return this.apRendererService.renderAnnounce(renote.uri ? renote.uri : `${this.config.url}/notes/${renote.id}`, note); } diff --git a/packages/backend/src/server/FileServerService.ts b/packages/backend/src/server/FileServerService.ts index 3cb353f2b3..e0b187f3cf 100644 --- a/packages/backend/src/server/FileServerService.ts +++ b/packages/backend/src/server/FileServerService.ts @@ -212,6 +212,8 @@ export class FileServerService { } reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(image.type) ? image.type : 'application/octet-stream'); + reply.header('Content-Length', file.file.size); + reply.header('Cache-Control', 'max-age=31536000, immutable'); reply.header('Content-Disposition', contentDisposition( 'inline', @@ -254,6 +256,7 @@ export class FileServerService { return fs.createReadStream(file.path); } else { reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.file.type) ? file.file.type : 'application/octet-stream'); + reply.header('Content-Length', file.file.size); reply.header('Cache-Control', 'max-age=31536000, immutable'); reply.header('Content-Disposition', contentDisposition('inline', file.filename)); @@ -528,9 +531,7 @@ export class FileServerService { if (!file.storedInternal) { if (!(file.isLink && file.uri)) return '204'; const result = await this.downloadAndDetectTypeFromUrl(file.uri); - if (!file.size) { - file.size = (await fs.promises.stat(result.path)).size; - } + file.size = (await fs.promises.stat(result.path)).size; // DB file.sizeは正確とは限らないので return { ...result, url: file.uri, diff --git a/packages/backend/src/server/HealthServerService.ts b/packages/backend/src/server/HealthServerService.ts new file mode 100644 index 0000000000..2c3ed85925 --- /dev/null +++ b/packages/backend/src/server/HealthServerService.ts @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Inject, Injectable } from '@nestjs/common'; +import * as Redis from 'ioredis'; +import { DataSource } from 'typeorm'; +import { bindThis } from '@/decorators.js'; +import { DI } from '@/di-symbols.js'; +import { readyRef } from '@/boot/ready.js'; +import type { FastifyInstance, FastifyPluginOptions } from 'fastify'; +import type { MeiliSearch } from 'meilisearch'; + +@Injectable() +export class HealthServerService { + constructor( + @Inject(DI.redis) + private redis: Redis.Redis, + + @Inject(DI.redisForPub) + private redisForPub: Redis.Redis, + + @Inject(DI.redisForSub) + private redisForSub: Redis.Redis, + + @Inject(DI.redisForTimelines) + private redisForTimelines: Redis.Redis, + + @Inject(DI.db) + private db: DataSource, + + @Inject(DI.meilisearch) + private meilisearch: MeiliSearch | null, + ) {} + + @bindThis + public createServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) { + fastify.get('/', async (request, reply) => { + reply.code(await Promise.all([ + new Promise((resolve, reject) => readyRef.value ? resolve() : reject()), + this.redis.ping(), + this.redisForPub.ping(), + this.redisForSub.ping(), + this.redisForTimelines.ping(), + this.db.query('SELECT 1'), + ...(this.meilisearch ? [this.meilisearch.health()] : []), + ]).then(() => 200, () => 503)); + reply.header('Cache-Control', 'no-store'); + }); + + done(); + } +} diff --git a/packages/backend/src/server/NodeinfoServerService.ts b/packages/backend/src/server/NodeinfoServerService.ts index d4f4c8b752..716bb0944b 100644 --- a/packages/backend/src/server/NodeinfoServerService.ts +++ b/packages/backend/src/server/NodeinfoServerService.ts @@ -36,12 +36,12 @@ export class NodeinfoServerService { @bindThis public getLinks() { return [{ - rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', - href: this.config.url + nodeinfo2_1path - }, { - rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0', - href: this.config.url + nodeinfo2_0path, - }]; + rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', + href: this.config.url + nodeinfo2_1path, + }, { + rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0', + href: this.config.url + nodeinfo2_0path, + }]; } @bindThis @@ -107,6 +107,7 @@ export class NodeinfoServerService { langs: meta.langs, tosUrl: meta.termsOfServiceUrl, privacyPolicyUrl: meta.privacyPolicyUrl, + inquiryUrl: meta.inquiryUrl, impressumUrl: meta.impressumUrl, donationUrl: meta.donationUrl, repositoryUrl: meta.repositoryUrl, diff --git a/packages/backend/src/server/ServerModule.ts b/packages/backend/src/server/ServerModule.ts index e0c4768ffc..39c8f67b8e 100644 --- a/packages/backend/src/server/ServerModule.ts +++ b/packages/backend/src/server/ServerModule.ts @@ -8,6 +8,7 @@ import { EndpointsModule } from '@/server/api/EndpointsModule.js'; import { CoreModule } from '@/core/CoreModule.js'; import { ApiCallService } from './api/ApiCallService.js'; import { FileServerService } from './FileServerService.js'; +import { HealthServerService } from './HealthServerService.js'; import { NodeinfoServerService } from './NodeinfoServerService.js'; import { ServerService } from './ServerService.js'; import { WellKnownServerService } from './WellKnownServerService.js'; @@ -58,6 +59,7 @@ import { ReversiGameChannelService } from './api/stream/channels/reversi-game.js ClientServerService, ClientLoggerService, FeedService, + HealthServerService, UrlPreviewService, ActivityPubServerService, FileServerService, diff --git a/packages/backend/src/server/ServerService.ts b/packages/backend/src/server/ServerService.ts index 5a456e09ad..9eddf434f7 100644 --- a/packages/backend/src/server/ServerService.ts +++ b/packages/backend/src/server/ServerService.ts @@ -18,7 +18,6 @@ import { DI } from '@/di-symbols.js'; import type Logger from '@/logger.js'; import * as Acct from '@/misc/acct.js'; import { genIdenticon } from '@/misc/gen-identicon.js'; -import { createTemp } from '@/misc/create-temp.js'; import { UserEntityService } from '@/core/entities/UserEntityService.js'; import { LoggerService } from '@/core/LoggerService.js'; import { bindThis } from '@/decorators.js'; @@ -29,6 +28,7 @@ import { ApiServerService } from './api/ApiServerService.js'; import { StreamingApiServerService } from './api/StreamingApiServerService.js'; import { WellKnownServerService } from './WellKnownServerService.js'; import { FileServerService } from './FileServerService.js'; +import { HealthServerService } from './HealthServerService.js'; import { ClientServerService } from './web/ClientServerService.js'; import { OpenApiServerService } from './api/openapi/OpenApiServerService.js'; import { MastodonApiServerService } from './api/mastodon/MastodonApiServerService.js'; @@ -64,6 +64,7 @@ export class ServerService implements OnApplicationShutdown { private wellKnownServerService: WellKnownServerService, private nodeinfoServerService: NodeinfoServerService, private fileServerService: FileServerService, + private healthServerService: HealthServerService, private clientServerService: ClientServerService, private globalEventService: GlobalEventService, private loggerService: LoggerService, @@ -111,6 +112,7 @@ export class ServerService implements OnApplicationShutdown { fastify.register(this.nodeinfoServerService.createServer); fastify.register(this.wellKnownServerService.createServer); fastify.register(this.oauth2ProviderService.createServer, { prefix: '/oauth' }); + fastify.register(this.healthServerService.createServer, { prefix: '/healthz' }); fastify.get<{ Params: { path: string }; Querystring: { static?: any; badge?: any; }; }>('/emoji/:path(.*)', async (request, reply) => { const path = request.params.path; @@ -122,12 +124,20 @@ export class ServerService implements OnApplicationShutdown { return; } - const name = path.split('@')[0].replace(/\.webp$/i, ''); - const host = path.split('@')[1]?.replace(/\.webp$/i, ''); + const emojiPath = path.replace(/\.webp$/i, ''); + const pathChunks = emojiPath.split('@'); + + if (pathChunks.length > 2) { + reply.code(400); + return; + } + + const name = pathChunks.shift(); + const host = pathChunks.pop(); const emoji = await this.emojisRepository.findOneBy({ // `@.` is the spec of ReactionService.decodeReaction - host: (host == null || host === '.') ? IsNull() : host, + host: (host === undefined || host === '.') ? IsNull() : host, name: name, }); @@ -186,9 +196,7 @@ export class ServerService implements OnApplicationShutdown { reply.header('Cache-Control', 'public, max-age=86400'); if ((await this.metaService.fetch()).enableIdenticonGeneration) { - const [temp, cleanup] = await createTemp(); - await genIdenticon(request.params.x, fs.createWriteStream(temp)); - return fs.createReadStream(temp).on('close', () => cleanup()); + return await genIdenticon(request.params.x); } else { return reply.redirect('/static-assets/avatar.png'); } diff --git a/packages/backend/src/server/api/ApiCallService.ts b/packages/backend/src/server/api/ApiCallService.ts index 9836689872..271ef80554 100644 --- a/packages/backend/src/server/api/ApiCallService.ts +++ b/packages/backend/src/server/api/ApiCallService.ts @@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto'; import * as fs from 'node:fs'; import * as stream from 'node:stream/promises'; import { Inject, Injectable } from '@nestjs/common'; +import * as Sentry from '@sentry/node'; import { DI } from '@/di-symbols.js'; import { getIpHash } from '@/misc/get-ip-hash.js'; import type { MiLocalUser, MiUser } from '@/models/User.js'; @@ -17,6 +18,7 @@ import { MetaService } from '@/core/MetaService.js'; import { createTemp } from '@/misc/create-temp.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; +import type { Config } from '@/config.js'; import { ApiError } from './error.js'; import { RateLimiterService } from './RateLimiterService.js'; import { ApiLoggerService } from './ApiLoggerService.js'; @@ -38,6 +40,9 @@ export class ApiCallService implements OnApplicationShutdown { private userIpHistoriesClearIntervalId: NodeJS.Timeout; constructor( + @Inject(DI.config) + private config: Config, + @Inject(DI.userIpsRepository) private userIpsRepository: UserIpsRepository, @@ -88,6 +93,48 @@ export class ApiCallService implements OnApplicationShutdown { } } + #onExecError(ep: IEndpoint, data: any, err: Error): void { + if (err instanceof ApiError || err instanceof AuthenticationError) { + throw err; + } else { + const errId = randomUUID(); + this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, { + ep: ep.name, + ps: data, + e: { + message: err.message, + code: err.name, + stack: err.stack, + id: errId, + }, + }); + console.error(err, errId); + + if (this.config.sentryForBackend) { + Sentry.captureMessage(`Internal error occurred in ${ep.name}: ${err.message}`, { + extra: { + ep: ep.name, + ps: data, + e: { + message: err.message, + code: err.name, + stack: err.stack, + id: errId, + }, + }, + }); + } + + throw new ApiError(null, { + e: { + message: err.message, + code: err.name, + id: errId, + }, + }); + } + } + @bindThis public handleRequest( endpoint: IEndpoint & { exec: any }, @@ -362,31 +409,11 @@ export class ApiCallService implements OnApplicationShutdown { } // API invoking - return await ep.exec(data, user, token, file, request.ip, request.headers).catch((err: Error) => { - if (err instanceof ApiError || err instanceof AuthenticationError) { - throw err; - } else { - const errId = randomUUID(); - this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, { - ep: ep.name, - ps: data, - e: { - message: err.message, - code: err.name, - stack: err.stack, - id: errId, - }, - }); - console.error(err, errId); - throw new ApiError(null, { - e: { - message: err.message, - code: err.name, - id: errId, - }, - }); - } - }); + if (this.config.sentryForBackend) { + return await Sentry.startSpan({ name: 'API: ' + ep.name }, () => ep.exec(data, user, token, file, request.ip, request.headers).catch((err: Error) => this.#onExecError(ep, data, err))); + } else { + return await ep.exec(data, user, token, file, request.ip, request.headers).catch((err: Error) => this.#onExecError(ep, data, err)); + } } @bindThis diff --git a/packages/backend/src/server/api/ApiServerService.ts b/packages/backend/src/server/api/ApiServerService.ts index e99244cdd0..4a5935f930 100644 --- a/packages/backend/src/server/api/ApiServerService.ts +++ b/packages/backend/src/server/api/ApiServerService.ts @@ -137,7 +137,7 @@ export class ApiServerService { const instances = await this.instancesRepository.find({ select: ['host'], where: { - isSuspended: false, + suspensionState: 'none', }, }); diff --git a/packages/backend/src/server/api/EndpointsModule.ts b/packages/backend/src/server/api/EndpointsModule.ts index f2945f477c..f44635fba0 100644 --- a/packages/backend/src/server/api/EndpointsModule.ts +++ b/packages/backend/src/server/api/EndpointsModule.ts @@ -88,6 +88,7 @@ import * as ep___admin_roles_unassign from './endpoints/admin/roles/unassign.js' import * as ep___admin_roles_updateDefaultPolicies from './endpoints/admin/roles/update-default-policies.js'; import * as ep___admin_roles_users from './endpoints/admin/roles/users.js'; import * as ep___announcements from './endpoints/announcements.js'; +import * as ep___announcements_show from './endpoints/announcements/show.js'; import * as ep___antennas_create from './endpoints/antennas/create.js'; import * as ep___antennas_delete from './endpoints/antennas/delete.js'; import * as ep___antennas_list from './endpoints/antennas/list.js'; @@ -473,6 +474,7 @@ const $admin_roles_unassign: Provider = { provide: 'ep:admin/roles/unassign', us const $admin_roles_updateDefaultPolicies: Provider = { provide: 'ep:admin/roles/update-default-policies', useClass: ep___admin_roles_updateDefaultPolicies.default }; const $admin_roles_users: Provider = { provide: 'ep:admin/roles/users', useClass: ep___admin_roles_users.default }; const $announcements: Provider = { provide: 'ep:announcements', useClass: ep___announcements.default }; +const $announcements_show: Provider = { provide: 'ep:announcements/show', useClass: ep___announcements_show.default }; const $antennas_create: Provider = { provide: 'ep:antennas/create', useClass: ep___antennas_create.default }; const $antennas_delete: Provider = { provide: 'ep:antennas/delete', useClass: ep___antennas_delete.default }; const $antennas_list: Provider = { provide: 'ep:antennas/list', useClass: ep___antennas_list.default }; @@ -862,6 +864,7 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__ $admin_roles_updateDefaultPolicies, $admin_roles_users, $announcements, + $announcements_show, $antennas_create, $antennas_delete, $antennas_list, @@ -1245,6 +1248,7 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__ $admin_roles_updateDefaultPolicies, $admin_roles_users, $announcements, + $announcements_show, $antennas_create, $antennas_delete, $antennas_list, diff --git a/packages/backend/src/server/api/endpoints.ts b/packages/backend/src/server/api/endpoints.ts index f83d2cacff..89f60933ef 100644 --- a/packages/backend/src/server/api/endpoints.ts +++ b/packages/backend/src/server/api/endpoints.ts @@ -88,6 +88,7 @@ import * as ep___admin_roles_unassign from './endpoints/admin/roles/unassign.js' import * as ep___admin_roles_updateDefaultPolicies from './endpoints/admin/roles/update-default-policies.js'; import * as ep___admin_roles_users from './endpoints/admin/roles/users.js'; import * as ep___announcements from './endpoints/announcements.js'; +import * as ep___announcements_show from './endpoints/announcements/show.js'; import * as ep___antennas_create from './endpoints/antennas/create.js'; import * as ep___antennas_delete from './endpoints/antennas/delete.js'; import * as ep___antennas_list from './endpoints/antennas/list.js'; @@ -471,6 +472,7 @@ const eps = [ ['admin/roles/update-default-policies', ep___admin_roles_updateDefaultPolicies], ['admin/roles/users', ep___admin_roles_users], ['announcements', ep___announcements], + ['announcements/show', ep___announcements_show], ['antennas/create', ep___antennas_create], ['antennas/delete', ep___antennas_delete], ['antennas/list', ep___antennas_list], diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts b/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts index f968813197..acd2494131 100644 --- a/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts +++ b/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts @@ -90,7 +90,7 @@ export default class extends Endpoint { // eslint- const addedEmoji = await this.customEmojiService.add({ driveFile, name: nameNfc, - category: emoji.category?.normalize('NFC'), + category: emoji.category?.normalize('NFC') ?? null, aliases: emoji.aliases?.map(a => a.normalize('NFC')), host: null, license: emoji.license, diff --git a/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts b/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts index 4ababae9f2..8b142910a6 100644 --- a/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts +++ b/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts @@ -47,13 +47,20 @@ export default class extends Endpoint { // eslint- throw new Error('instance not found'); } + const isSuspendedBefore = instance.suspensionState !== 'none'; + let suspensionState: undefined | 'manuallySuspended' | 'none'; + + if (ps.isSuspended != null && isSuspendedBefore !== ps.isSuspended) { + suspensionState = ps.isSuspended ? 'manuallySuspended' : 'none'; + } + await this.federatedInstanceService.update(instance.id, { - isSuspended: ps.isSuspended, + suspensionState, isNSFW: ps.isNSFW, moderationNote: ps.moderationNote, }); - if (ps.isSuspended != null && instance.isSuspended !== ps.isSuspended) { + if (ps.isSuspended != null && isSuspendedBefore !== ps.isSuspended) { if (ps.isSuspended) { this.moderationLogService.log(me, 'suspendRemoteInstance', { id: instance.id, diff --git a/packages/backend/src/server/api/endpoints/admin/meta.ts b/packages/backend/src/server/api/endpoints/admin/meta.ts index 34454c276e..ca4d63b834 100644 --- a/packages/backend/src/server/api/endpoints/admin/meta.ts +++ b/packages/backend/src/server/api/endpoints/admin/meta.ts @@ -458,6 +458,10 @@ export const meta = { type: 'string', optional: false, nullable: true, }, + inquiryUrl: { + type: 'string', + optional: false, nullable: true, + }, repositoryUrl: { type: 'string', optional: false, nullable: true, @@ -465,6 +469,8 @@ export const meta = { summalyProxy: { type: 'string', optional: false, nullable: true, + deprecated: true, + description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.', }, themeColor: { type: 'string', @@ -482,6 +488,30 @@ export const meta = { type: 'string', optional: false, nullable: false, }, + urlPreviewEnabled: { + type: 'boolean', + optional: false, nullable: false, + }, + urlPreviewTimeout: { + type: 'number', + optional: false, nullable: false, + }, + urlPreviewMaximumContentLength: { + type: 'number', + optional: false, nullable: false, + }, + urlPreviewRequireContentLength: { + type: 'boolean', + optional: false, nullable: false, + }, + urlPreviewUserAgent: { + type: 'string', + optional: false, nullable: true, + }, + urlPreviewSummaryProxyUrl: { + type: 'string', + optional: false, nullable: true, + }, }, }, } as const; @@ -519,6 +549,7 @@ export default class extends Endpoint { // eslint- impressumUrl: instance.impressumUrl, donationUrl: instance.donationUrl, privacyPolicyUrl: instance.privacyPolicyUrl, + inquiryUrl: instance.inquiryUrl, disableRegistration: instance.disableRegistration, emailRequiredForSignup: instance.emailRequiredForSignup, approvalRequiredForSignup: instance.approvalRequiredForSignup, @@ -569,7 +600,6 @@ export default class extends Endpoint { // eslint- enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos, enableBotTrending: instance.enableBotTrending, proxyAccountId: instance.proxyAccountId, - summalyProxy: instance.summalyProxy, email: instance.email, smtpSecure: instance.smtpSecure, smtpHost: instance.smtpHost, @@ -616,6 +646,13 @@ export default class extends Endpoint { // eslint- perUserHomeTimelineCacheMax: instance.perUserHomeTimelineCacheMax, perUserListTimelineCacheMax: instance.perUserListTimelineCacheMax, notesPerOneAd: instance.notesPerOneAd, + summalyProxy: instance.urlPreviewSummaryProxyUrl, + urlPreviewEnabled: instance.urlPreviewEnabled, + urlPreviewTimeout: instance.urlPreviewTimeout, + urlPreviewMaximumContentLength: instance.urlPreviewMaximumContentLength, + urlPreviewRequireContentLength: instance.urlPreviewRequireContentLength, + urlPreviewUserAgent: instance.urlPreviewUserAgent, + urlPreviewSummaryProxyUrl: instance.urlPreviewSummaryProxyUrl, }; }); } diff --git a/packages/backend/src/server/api/endpoints/admin/nsfw-user.ts b/packages/backend/src/server/api/endpoints/admin/nsfw-user.ts index 2a47abe03c..d3fa4251dd 100644 --- a/packages/backend/src/server/api/endpoints/admin/nsfw-user.ts +++ b/packages/backend/src/server/api/endpoints/admin/nsfw-user.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import type { UsersRepository, UserProfilesRepository } from '@/models/_.js'; diff --git a/packages/backend/src/server/api/endpoints/admin/roles/users.ts b/packages/backend/src/server/api/endpoints/admin/roles/users.ts index 45758d4f50..198166bec2 100644 --- a/packages/backend/src/server/api/endpoints/admin/roles/users.ts +++ b/packages/backend/src/server/api/endpoints/admin/roles/users.ts @@ -89,10 +89,13 @@ export default class extends Endpoint { // eslint- .limit(ps.limit) .getMany(); + const _users = assigns.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me, { schema: 'UserDetailed' }) + .then(users => new Map(users.map(u => [u.id, u]))); return await Promise.all(assigns.map(async assign => ({ id: assign.id, createdAt: this.idService.parse(assign.id).date.toISOString(), - user: await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }), + user: _userMap.get(assign.userId) ?? await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }), expiresAt: assign.expiresAt?.toISOString() ?? null, }))); }); diff --git a/packages/backend/src/server/api/endpoints/admin/show-users.ts b/packages/backend/src/server/api/endpoints/admin/show-users.ts index 685da928e3..5f16519403 100644 --- a/packages/backend/src/server/api/endpoints/admin/show-users.ts +++ b/packages/backend/src/server/api/endpoints/admin/show-users.ts @@ -16,7 +16,7 @@ export const meta = { requireCredential: true, requireModerator: true, - kind: 'read:admin:show-users', + kind: 'read:admin:show-user', res: { type: 'array', diff --git a/packages/backend/src/server/api/endpoints/admin/silence-user.ts b/packages/backend/src/server/api/endpoints/admin/silence-user.ts index 007bed5c03..7e6045049a 100644 --- a/packages/backend/src/server/api/endpoints/admin/silence-user.ts +++ b/packages/backend/src/server/api/endpoints/admin/silence-user.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import type { UsersRepository } from '@/models/_.js'; diff --git a/packages/backend/src/server/api/endpoints/admin/unnsfw-user.ts b/packages/backend/src/server/api/endpoints/admin/unnsfw-user.ts index 013e7771ba..26588365e1 100644 --- a/packages/backend/src/server/api/endpoints/admin/unnsfw-user.ts +++ b/packages/backend/src/server/api/endpoints/admin/unnsfw-user.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import type { UsersRepository, UserProfilesRepository } from '@/models/_.js'; diff --git a/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts b/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts index 5e514ccda6..f92be0d8e0 100644 --- a/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts +++ b/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import type { UsersRepository } from '@/models/_.js'; diff --git a/packages/backend/src/server/api/endpoints/admin/update-meta.ts b/packages/backend/src/server/api/endpoints/admin/update-meta.ts index 7fea7d969e..015a1e1f7c 100644 --- a/packages/backend/src/server/api/endpoints/admin/update-meta.ts +++ b/packages/backend/src/server/api/endpoints/admin/update-meta.ts @@ -93,7 +93,6 @@ export const paramDef = { type: 'string', }, }, - summalyProxy: { type: 'string', nullable: true }, deeplAuthKey: { type: 'string', nullable: true }, deeplIsPro: { type: 'boolean' }, deeplFreeMode: { type: 'boolean' }, @@ -114,6 +113,7 @@ export const paramDef = { impressumUrl: { type: 'string', nullable: true }, donationUrl: { type: 'string', nullable: true }, privacyPolicyUrl: { type: 'string', nullable: true }, + inquiryUrl: { type: 'string', nullable: true }, useObjectStorage: { type: 'boolean' }, objectStorageBaseUrl: { type: 'string', nullable: true }, objectStorageBucket: { type: 'string', nullable: true }, @@ -158,6 +158,16 @@ export const paramDef = { type: 'string', }, }, + summalyProxy: { + type: 'string', nullable: true, + description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.', + }, + urlPreviewEnabled: { type: 'boolean' }, + urlPreviewTimeout: { type: 'integer' }, + urlPreviewMaximumContentLength: { type: 'integer' }, + urlPreviewRequireContentLength: { type: 'boolean' }, + urlPreviewUserAgent: { type: 'string', nullable: true }, + urlPreviewSummaryProxyUrl: { type: 'string', nullable: true }, }, required: [], } as const; @@ -357,10 +367,6 @@ export default class extends Endpoint { // eslint- set.langs = ps.langs.filter(Boolean); } - if (ps.summalyProxy !== undefined) { - set.summalyProxy = ps.summalyProxy; - } - if (ps.enableEmail !== undefined) { set.enableEmail = ps.enableEmail; } @@ -425,6 +431,10 @@ export default class extends Endpoint { // eslint- set.privacyPolicyUrl = ps.privacyPolicyUrl; } + if (ps.inquiryUrl !== undefined) { + set.inquiryUrl = ps.inquiryUrl; + } + if (ps.useObjectStorage !== undefined) { set.useObjectStorage = ps.useObjectStorage; } @@ -609,6 +619,32 @@ export default class extends Endpoint { // eslint- set.bannedEmailDomains = ps.bannedEmailDomains; } + if (ps.urlPreviewEnabled !== undefined) { + set.urlPreviewEnabled = ps.urlPreviewEnabled; + } + + if (ps.urlPreviewTimeout !== undefined) { + set.urlPreviewTimeout = ps.urlPreviewTimeout; + } + + if (ps.urlPreviewMaximumContentLength !== undefined) { + set.urlPreviewMaximumContentLength = ps.urlPreviewMaximumContentLength; + } + + if (ps.urlPreviewRequireContentLength !== undefined) { + set.urlPreviewRequireContentLength = ps.urlPreviewRequireContentLength; + } + + if (ps.urlPreviewUserAgent !== undefined) { + const value = (ps.urlPreviewUserAgent ?? '').trim(); + set.urlPreviewUserAgent = value === '' ? null : ps.urlPreviewUserAgent; + } + + if (ps.summalyProxy !== undefined || ps.urlPreviewSummaryProxyUrl !== undefined) { + const value = ((ps.urlPreviewSummaryProxyUrl ?? ps.summalyProxy) ?? '').trim(); + set.urlPreviewSummaryProxyUrl = value === '' ? null : value; + } + const before = await this.metaService.fetch(true); await this.metaService.update(set); diff --git a/packages/backend/src/server/api/endpoints/announcements.ts b/packages/backend/src/server/api/endpoints/announcements.ts index 3b12f5b62c..ff8dd73605 100644 --- a/packages/backend/src/server/api/endpoints/announcements.ts +++ b/packages/backend/src/server/api/endpoints/announcements.ts @@ -7,9 +7,9 @@ import { Inject, Injectable } from '@nestjs/common'; import { Brackets } from 'typeorm'; import { Endpoint } from '@/server/api/endpoint-base.js'; import { QueryService } from '@/core/QueryService.js'; -import { AnnouncementService } from '@/core/AnnouncementService.js'; +import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js'; import { DI } from '@/di-symbols.js'; -import type { AnnouncementReadsRepository, AnnouncementsRepository } from '@/models/_.js'; +import type { AnnouncementsRepository } from '@/models/_.js'; export const meta = { tags: ['meta'], @@ -44,11 +44,8 @@ export default class extends Endpoint { // eslint- @Inject(DI.announcementsRepository) private announcementsRepository: AnnouncementsRepository, - @Inject(DI.announcementReadsRepository) - private announcementReadsRepository: AnnouncementReadsRepository, - private queryService: QueryService, - private announcementService: AnnouncementService, + private announcementEntityService: AnnouncementEntityService, ) { super(meta, paramDef, async (ps, me) => { const query = this.queryService.makePaginationQuery(this.announcementsRepository.createQueryBuilder('announcement'), ps.sinceId, ps.untilId) @@ -60,7 +57,7 @@ export default class extends Endpoint { // eslint- const announcements = await query.limit(ps.limit).getMany(); - return this.announcementService.packMany(announcements, me); + return this.announcementEntityService.packMany(announcements, me); }); } } diff --git a/packages/backend/src/server/api/endpoints/announcements/show.ts b/packages/backend/src/server/api/endpoints/announcements/show.ts new file mode 100644 index 0000000000..6312a0a54c --- /dev/null +++ b/packages/backend/src/server/api/endpoints/announcements/show.ts @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Injectable } from '@nestjs/common'; +import { EntityNotFoundError } from 'typeorm'; +import { Endpoint } from '@/server/api/endpoint-base.js'; +import { AnnouncementService } from '@/core/AnnouncementService.js'; +import { ApiError } from '../../error.js'; + +export const meta = { + tags: ['meta'], + + requireCredential: false, + + res: { + type: 'object', + optional: false, nullable: false, + ref: 'Announcement', + }, + + errors: { + noSuchAnnouncement: { + message: 'No such announcement.', + code: 'NO_SUCH_ANNOUNCEMENT', + id: 'b57b5e1d-4f49-404a-9edb-46b00268f121', + }, + }, +} as const; + +export const paramDef = { + type: 'object', + properties: { + announcementId: { type: 'string', format: 'misskey:id' }, + }, + required: ['announcementId'], +} as const; + +@Injectable() +export default class extends Endpoint { // eslint-disable-line import/no-default-export + constructor( + private announcementService: AnnouncementService, + ) { + super(meta, paramDef, async (ps, me) => { + try { + return await this.announcementService.getAnnouncement(ps.announcementId, me); + } catch (err) { + if (err instanceof EntityNotFoundError) throw new ApiError(meta.errors.noSuchAnnouncement); + throw err; + } + }); + } +} diff --git a/packages/backend/src/server/api/endpoints/antennas/create.ts b/packages/backend/src/server/api/endpoints/antennas/create.ts index 191de8f833..6b7bacb054 100644 --- a/packages/backend/src/server/api/endpoints/antennas/create.ts +++ b/packages/backend/src/server/api/endpoints/antennas/create.ts @@ -64,11 +64,11 @@ export const paramDef = { } }, caseSensitive: { type: 'boolean' }, localOnly: { type: 'boolean' }, + excludeBots: { type: 'boolean' }, withReplies: { type: 'boolean' }, withFile: { type: 'boolean' }, - notify: { type: 'boolean' }, }, - required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'], + required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile'], } as const; @Injectable() @@ -124,9 +124,9 @@ export default class extends Endpoint { // eslint- users: ps.users, caseSensitive: ps.caseSensitive, localOnly: ps.localOnly, + excludeBots: ps.excludeBots, withReplies: ps.withReplies, withFile: ps.withFile, - notify: ps.notify, }).then(x => this.antennasRepository.findOneByOrFail(x.identifiers[0])); this.globalEventService.publishInternalEvent('antennaCreated', antenna); diff --git a/packages/backend/src/server/api/endpoints/antennas/update.ts b/packages/backend/src/server/api/endpoints/antennas/update.ts index 459729f61f..0c30bca9e0 100644 --- a/packages/backend/src/server/api/endpoints/antennas/update.ts +++ b/packages/backend/src/server/api/endpoints/antennas/update.ts @@ -63,11 +63,11 @@ export const paramDef = { } }, caseSensitive: { type: 'boolean' }, localOnly: { type: 'boolean' }, + excludeBots: { type: 'boolean' }, withReplies: { type: 'boolean' }, withFile: { type: 'boolean' }, - notify: { type: 'boolean' }, }, - required: ['antennaId', 'name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'], + required: ['antennaId'], } as const; @Injectable() @@ -83,8 +83,10 @@ export default class extends Endpoint { // eslint- private globalEventService: GlobalEventService, ) { super(meta, paramDef, async (ps, me) => { - if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) { - throw new Error('either keywords or excludeKeywords is required.'); + if (ps.keywords && ps.excludeKeywords) { + if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) { + throw new Error('either keywords or excludeKeywords is required.'); + } } // Fetch the antenna const antenna = await this.antennasRepository.findOneBy({ @@ -98,7 +100,7 @@ export default class extends Endpoint { // eslint- let userList; - if (ps.src === 'list' && ps.userListId) { + if ((ps.src === 'list' || antenna.src === 'list') && ps.userListId) { userList = await this.userListsRepository.findOneBy({ id: ps.userListId, userId: me.id, @@ -112,15 +114,15 @@ export default class extends Endpoint { // eslint- await this.antennasRepository.update(antenna.id, { name: ps.name, src: ps.src, - userListId: userList ? userList.id : null, + userListId: ps.userListId !== undefined ? userList ? userList.id : null : undefined, keywords: ps.keywords, excludeKeywords: ps.excludeKeywords, users: ps.users, caseSensitive: ps.caseSensitive, localOnly: ps.localOnly, + excludeBots: ps.excludeBots, withReplies: ps.withReplies, withFile: ps.withFile, - notify: ps.notify, isActive: true, lastUsedAt: new Date(), }); diff --git a/packages/backend/src/server/api/endpoints/channels/timeline.ts b/packages/backend/src/server/api/endpoints/channels/timeline.ts index 295fc5686c..9369481649 100644 --- a/packages/backend/src/server/api/endpoints/channels/timeline.ts +++ b/packages/backend/src/server/api/endpoints/channels/timeline.ts @@ -16,6 +16,7 @@ import { MetaService } from '@/core/MetaService.js'; import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js'; import { MiLocalUser } from '@/models/User.js'; import { ApiError } from '../../error.js'; +import { Brackets } from 'typeorm'; export const meta = { tags: ['notes', 'channels'], diff --git a/packages/backend/src/server/api/endpoints/drive/files/find.ts b/packages/backend/src/server/api/endpoints/drive/files/find.ts index 595a6957b2..502d42f9e0 100644 --- a/packages/backend/src/server/api/endpoints/drive/files/find.ts +++ b/packages/backend/src/server/api/endpoints/drive/files/find.ts @@ -54,7 +54,7 @@ export default class extends Endpoint { // eslint- folderId: ps.folderId ?? IsNull(), }); - return await Promise.all(files.map(file => this.driveFileEntityService.pack(file, { self: true }))); + return await this.driveFileEntityService.packMany(files, { self: true }); }); } } diff --git a/packages/backend/src/server/api/endpoints/federation/instances.ts b/packages/backend/src/server/api/endpoints/federation/instances.ts index 4064a415a4..c3f2247b69 100644 --- a/packages/backend/src/server/api/endpoints/federation/instances.ts +++ b/packages/backend/src/server/api/endpoints/federation/instances.ts @@ -125,9 +125,9 @@ export default class extends Endpoint { // eslint- if (typeof ps.suspended === 'boolean') { if (ps.suspended) { - query.andWhere('instance.isSuspended = TRUE'); + query.andWhere('instance.suspensionState != \'none\''); } else { - query.andWhere('instance.isSuspended = FALSE'); + query.andWhere('instance.suspensionState = \'none\''); } } diff --git a/packages/backend/src/server/api/endpoints/fetch-rss.ts b/packages/backend/src/server/api/endpoints/fetch-rss.ts index 2085b06365..ba48b0119e 100644 --- a/packages/backend/src/server/api/endpoints/fetch-rss.ts +++ b/packages/backend/src/server/api/endpoints/fetch-rss.ts @@ -20,13 +20,188 @@ export const meta = { res: { type: 'object', properties: { + image: { + type: 'object', + optional: true, + properties: { + link: { + type: 'string', + optional: true, + }, + url: { + type: 'string', + optional: false, + }, + title: { + type: 'string', + optional: true, + }, + }, + }, + paginationLinks: { + type: 'object', + optional: true, + properties: { + self: { + type: 'string', + optional: true, + }, + first: { + type: 'string', + optional: true, + }, + next: { + type: 'string', + optional: true, + }, + last: { + type: 'string', + optional: true, + }, + prev: { + type: 'string', + optional: true, + }, + }, + }, + link: { + type: 'string', + optional: true, + }, + title: { + type: 'string', + optional: true, + }, items: { type: 'array', + optional: false, items: { type: 'object', + properties: { + link: { + type: 'string', + optional: true, + }, + guid: { + type: 'string', + optional: true, + }, + title: { + type: 'string', + optional: true, + }, + pubDate: { + type: 'string', + optional: true, + }, + creator: { + type: 'string', + optional: true, + }, + summary: { + type: 'string', + optional: true, + }, + content: { + type: 'string', + optional: true, + }, + isoDate: { + type: 'string', + optional: true, + }, + categories: { + type: 'array', + optional: true, + items: { + type: 'string', + }, + }, + contentSnippet: { + type: 'string', + optional: true, + }, + enclosure: { + type: 'object', + optional: true, + properties: { + url: { + type: 'string', + optional: false, + }, + length: { + type: 'number', + optional: true, + }, + type: { + type: 'string', + optional: true, + }, + }, + }, + }, }, - } - } + }, + feedUrl: { + type: 'string', + optional: true, + }, + description: { + type: 'string', + optional: true, + }, + itunes: { + type: 'object', + optional: true, + additionalProperties: true, + properties: { + image: { + type: 'string', + optional: true, + }, + owner: { + type: 'object', + optional: true, + properties: { + name: { + type: 'string', + optional: true, + }, + email: { + type: 'string', + optional: true, + }, + }, + }, + author: { + type: 'string', + optional: true, + }, + summary: { + type: 'string', + optional: true, + }, + explicit: { + type: 'string', + optional: true, + }, + categories: { + type: 'array', + optional: true, + items: { + type: 'string', + }, + }, + keywords: { + type: 'array', + optional: true, + items: { + type: 'string', + }, + }, + }, + }, + }, }, } as const; diff --git a/packages/backend/src/server/api/endpoints/flash/create.ts b/packages/backend/src/server/api/endpoints/flash/create.ts index 584d167a29..361496e17e 100644 --- a/packages/backend/src/server/api/endpoints/flash/create.ts +++ b/packages/backend/src/server/api/endpoints/flash/create.ts @@ -44,6 +44,7 @@ export const paramDef = { permissions: { type: 'array', items: { type: 'string', } }, + visibility: { type: 'string', enum: ['public', 'private'], default: 'public' }, }, required: ['title', 'summary', 'script', 'permissions'], } as const; @@ -66,6 +67,7 @@ export default class extends Endpoint { // eslint- summary: ps.summary, script: ps.script, permissions: ps.permissions, + visibility: ps.visibility, }).then(x => this.flashsRepository.findOneByOrFail(x.identifiers[0])); return await this.flashEntityService.pack(flash); diff --git a/packages/backend/src/server/api/endpoints/following/requests/list.ts b/packages/backend/src/server/api/endpoints/following/requests/list.ts index 88f559138b..fa59e38976 100644 --- a/packages/backend/src/server/api/endpoints/following/requests/list.ts +++ b/packages/backend/src/server/api/endpoints/following/requests/list.ts @@ -71,7 +71,7 @@ export default class extends Endpoint { // eslint- .limit(ps.limit) .getMany(); - return await Promise.all(requests.map(req => this.followRequestEntityService.pack(req))); + return await this.followRequestEntityService.packMany(requests, me); }); } } diff --git a/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts b/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts index 74ee90b3dd..a4e61a0e8f 100644 --- a/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts +++ b/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts @@ -97,10 +97,10 @@ export default class extends Endpoint { } const keyInfo = await this.webAuthnService.verifyRegistration(me.id, ps.credential); + const keyId = keyInfo.credentialID; - const credentialId = Buffer.from(keyInfo.credentialID).toString('base64url'); await this.userSecurityKeysRepository.insert({ - id: credentialId, + id: keyId, userId: me.id, name: ps.name, publicKey: Buffer.from(keyInfo.credentialPublicKey).toString('base64url'), @@ -117,7 +117,7 @@ export default class extends Endpoint { })); return { - id: credentialId, + id: keyId, name: ps.name, }; }); diff --git a/packages/backend/src/server/api/endpoints/i/import-blocking.ts b/packages/backend/src/server/api/endpoints/i/import-blocking.ts index 8ddbe5663e..2606108539 100644 --- a/packages/backend/src/server/api/endpoints/i/import-blocking.ts +++ b/packages/backend/src/server/api/endpoints/i/import-blocking.ts @@ -75,7 +75,7 @@ export default class extends Endpoint { // eslint- const checkMoving = await this.accountMoveService.validateAlsoKnownAs( me, - (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(), + (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(), true, ); if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile); diff --git a/packages/backend/src/server/api/endpoints/i/import-following.ts b/packages/backend/src/server/api/endpoints/i/import-following.ts index 390dd9cd71..d5e824df27 100644 --- a/packages/backend/src/server/api/endpoints/i/import-following.ts +++ b/packages/backend/src/server/api/endpoints/i/import-following.ts @@ -75,7 +75,7 @@ export default class extends Endpoint { // eslint- const checkMoving = await this.accountMoveService.validateAlsoKnownAs( me, - (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(), + (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(), true, ); if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile); diff --git a/packages/backend/src/server/api/endpoints/i/import-muting.ts b/packages/backend/src/server/api/endpoints/i/import-muting.ts index 51a9cdf5a5..0f5800404e 100644 --- a/packages/backend/src/server/api/endpoints/i/import-muting.ts +++ b/packages/backend/src/server/api/endpoints/i/import-muting.ts @@ -75,7 +75,7 @@ export default class extends Endpoint { // eslint- const checkMoving = await this.accountMoveService.validateAlsoKnownAs( me, - (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(), + (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(), true, ); if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile); diff --git a/packages/backend/src/server/api/endpoints/i/import-notes.ts b/packages/backend/src/server/api/endpoints/i/import-notes.ts index 4e00163550..91ef12c3e3 100644 --- a/packages/backend/src/server/api/endpoints/i/import-notes.ts +++ b/packages/backend/src/server/api/endpoints/i/import-notes.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import ms from 'ms'; import { Endpoint } from '@/server/api/endpoint-base.js'; @@ -59,7 +64,7 @@ export default class extends Endpoint { // eslint- const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); if (file == null) throw new ApiError(meta.errors.noSuchFile); - + if (file.size === 0) throw new ApiError(meta.errors.emptyFile); if ((await this.roleService.getUserPolicies(me.id)).canImportNotes === false) { diff --git a/packages/backend/src/server/api/endpoints/i/import-user-lists.ts b/packages/backend/src/server/api/endpoints/i/import-user-lists.ts index a3b67301a7..bacdd5c88f 100644 --- a/packages/backend/src/server/api/endpoints/i/import-user-lists.ts +++ b/packages/backend/src/server/api/endpoints/i/import-user-lists.ts @@ -74,7 +74,7 @@ export default class extends Endpoint { // eslint- const checkMoving = await this.accountMoveService.validateAlsoKnownAs( me, - (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(), + (old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(), true, ); if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile); diff --git a/packages/backend/src/server/api/endpoints/i/notifications.ts b/packages/backend/src/server/api/endpoints/i/notifications.ts index 594e8b95c8..5e97b90f99 100644 --- a/packages/backend/src/server/api/endpoints/i/notifications.ts +++ b/packages/backend/src/server/api/endpoints/i/notifications.ts @@ -7,7 +7,7 @@ import { In } from 'typeorm'; import * as Redis from 'ioredis'; import { Inject, Injectable } from '@nestjs/common'; import type { NotesRepository } from '@/models/_.js'; -import { obsoleteNotificationTypes, notificationTypes, FilterUnionByProperty } from '@/types.js'; +import { FilterUnionByProperty, notificationTypes, obsoleteNotificationTypes } from '@/types.js'; import { Endpoint } from '@/server/api/endpoint-base.js'; import { NoteReadService } from '@/core/NoteReadService.js'; import { NotificationEntityService } from '@/core/entities/NotificationEntityService.js'; @@ -84,27 +84,51 @@ export default class extends Endpoint { // eslint- const includeTypes = ps.includeTypes && ps.includeTypes.filter(type => !(obsoleteNotificationTypes).includes(type as any)) as typeof notificationTypes[number][]; const excludeTypes = ps.excludeTypes && ps.excludeTypes.filter(type => !(obsoleteNotificationTypes).includes(type as any)) as typeof notificationTypes[number][]; - const limit = ps.limit + (ps.untilId ? 1 : 0) + (ps.sinceId ? 1 : 0); // untilIdに指定したものも含まれるため+1 - const notificationsRes = await this.redisClient.xrevrange( - `notificationTimeline:${me.id}`, - ps.untilId ? this.idService.parse(ps.untilId).date.getTime() : '+', - ps.sinceId ? this.idService.parse(ps.sinceId).date.getTime() : '-', - 'COUNT', limit); + let sinceTime = ps.sinceId ? this.idService.parse(ps.sinceId).date.getTime().toString() : null; + let untilTime = ps.untilId ? this.idService.parse(ps.untilId).date.getTime().toString() : null; - if (notificationsRes.length === 0) { - return []; - } + let notifications: MiNotification[]; + for (;;) { + let notificationsRes: [id: string, fields: string[]][]; - let notifications = notificationsRes.map(x => JSON.parse(x[1][1])).filter(x => x.id !== ps.untilId && x !== ps.sinceId) as MiNotification[]; + // sinceidのみの場合は古い順、そうでない場合は新しい順。 QueryService.makePaginationQueryも参照 + if (sinceTime && !untilTime) { + notificationsRes = await this.redisClient.xrange( + `notificationTimeline:${me.id}`, + '(' + sinceTime, + '+', + 'COUNT', ps.limit); + } else { + notificationsRes = await this.redisClient.xrevrange( + `notificationTimeline:${me.id}`, + untilTime ? '(' + untilTime : '+', + sinceTime ? '(' + sinceTime : '-', + 'COUNT', ps.limit); + } - if (includeTypes && includeTypes.length > 0) { - notifications = notifications.filter(notification => includeTypes.includes(notification.type)); - } else if (excludeTypes && excludeTypes.length > 0) { - notifications = notifications.filter(notification => !excludeTypes.includes(notification.type)); - } + if (notificationsRes.length === 0) { + return []; + } - if (notifications.length === 0) { - return []; + notifications = notificationsRes.map(x => JSON.parse(x[1][1])) as MiNotification[]; + + if (includeTypes && includeTypes.length > 0) { + notifications = notifications.filter(notification => includeTypes.includes(notification.type)); + } else if (excludeTypes && excludeTypes.length > 0) { + notifications = notifications.filter(notification => !excludeTypes.includes(notification.type)); + } + + if (notifications.length !== 0) { + // 通知が1件以上ある場合は返す + break; + } + + // フィルタしたことで通知が0件になった場合、次のページを取得する + if (ps.sinceId && !ps.untilId) { + sinceTime = notificationsRes[notificationsRes.length - 1][0]; + } else { + untilTime = notificationsRes[notificationsRes.length - 1][0]; + } } // Mark all as read diff --git a/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts b/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts index bb471284c9..3aa256077e 100644 --- a/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts +++ b/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import type { RegistryItemsRepository } from '@/models/_.js'; diff --git a/packages/backend/src/server/api/endpoints/i/update-email.ts b/packages/backend/src/server/api/endpoints/i/update-email.ts index 08a8301bd1..7332026d84 100644 --- a/packages/backend/src/server/api/endpoints/i/update-email.ts +++ b/packages/backend/src/server/api/endpoints/i/update-email.ts @@ -16,6 +16,7 @@ import { DI } from '@/di-symbols.js'; import { GlobalEventService } from '@/core/GlobalEventService.js'; import { L_CHARS, secureRndstr } from '@/misc/secure-rndstr.js'; import { UserAuthService } from '@/core/UserAuthService.js'; +import { MetaService } from '@/core/MetaService.js'; import { ApiError } from '../../error.js'; export const meta = { @@ -40,6 +41,12 @@ export const meta = { code: 'UNAVAILABLE', id: 'a2defefb-f220-8849-0af6-17f816099323', }, + + emailRequired: { + message: 'Email address is required.', + code: 'EMAIL_REQUIRED', + id: '324c7a88-59f2-492f-903f-89134f93e47e', + }, }, res: { @@ -67,6 +74,7 @@ export default class extends Endpoint { // eslint- @Inject(DI.userProfilesRepository) private userProfilesRepository: UserProfilesRepository, + private metaService: MetaService, private userEntityService: UserEntityService, private emailService: EmailService, private userAuthService: UserAuthService, @@ -98,6 +106,8 @@ export default class extends Endpoint { // eslint- if (!res.available) { throw new ApiError(meta.errors.unavailable); } + } else if ((await this.metaService.fetch()).emailRequiredForSignup) { + throw new ApiError(meta.errors.emailRequired); } await this.userProfilesRepository.update(me.id, { diff --git a/packages/backend/src/server/api/endpoints/i/update.ts b/packages/backend/src/server/api/endpoints/i/update.ts index 06edb28578..aa2f85845f 100644 --- a/packages/backend/src/server/api/endpoints/i/update.ts +++ b/packages/backend/src/server/api/endpoints/i/update.ts @@ -530,26 +530,32 @@ export default class extends Endpoint { // eslint- private async verifyLink(url: string, user: MiLocalUser) { if (!safeForSql(url)) return; - const html = await this.httpRequestService.getHtml(url); + try { + const html = await this.httpRequestService.getHtml(url); - const { window } = new JSDOM(html); - const doc = window.document; + const { window } = new JSDOM(html); + const doc = window.document; - const myLink = `${this.config.url}/@${user.username}`; + const myLink = `${this.config.url}/@${user.username}`; - const aEls = Array.from(doc.getElementsByTagName('a')); - const linkEls = Array.from(doc.getElementsByTagName('link')); + const aEls = Array.from(doc.getElementsByTagName('a')); + const linkEls = Array.from(doc.getElementsByTagName('link')); - const includesMyLink = aEls.some(a => a.href === myLink); - const includesRelMeLinks = [...aEls, ...linkEls].some(link => link.rel === 'me' && link.href === myLink); + const includesMyLink = aEls.some(a => a.href === myLink); + const includesRelMeLinks = [...aEls, ...linkEls].some(link => link.rel === 'me' && link.href === myLink); - if (includesMyLink || includesRelMeLinks) { - await this.userProfilesRepository.createQueryBuilder('profile').update() - .where('userId = :userId', { userId: user.id }) - .set({ - verifiedLinks: () => `array_append("verifiedLinks", '${url}')`, // ここでSQLインジェクションされそうなのでとりあえず safeForSql で弾いている - }) - .execute(); + if (includesMyLink || includesRelMeLinks) { + await this.userProfilesRepository.createQueryBuilder('profile').update() + .where('userId = :userId', { userId: user.id }) + .set({ + verifiedLinks: () => `array_append("verifiedLinks", '${url}')`, // ここでSQLインジェクションされそうなのでとりあえず safeForSql で弾いている + }) + .execute(); + } + + window.close(); + } catch (err) { + // なにもしない } } } diff --git a/packages/backend/src/server/api/endpoints/notes/create.ts b/packages/backend/src/server/api/endpoints/notes/create.ts index fe2dafa98e..626f03b758 100644 --- a/packages/backend/src/server/api/endpoints/notes/create.ts +++ b/packages/backend/src/server/api/endpoints/notes/create.ts @@ -16,7 +16,7 @@ import { Endpoint } from '@/server/api/endpoint-base.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { NoteCreateService } from '@/core/NoteCreateService.js'; import { DI } from '@/di-symbols.js'; -import { isPureRenote } from '@/misc/is-pure-renote.js'; +import { isQuote, isRenote } from '@/misc/is-renote.js'; import { MetaService } from '@/core/MetaService.js'; import { UtilityService } from '@/core/UtilityService.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; @@ -287,7 +287,7 @@ export default class extends Endpoint { // eslint- if (renote == null) { throw new ApiError(meta.errors.noSuchRenoteTarget); - } else if (isPureRenote(renote)) { + } else if (isRenote(renote) && !isQuote(renote)) { throw new ApiError(meta.errors.cannotReRenote); } @@ -333,7 +333,7 @@ export default class extends Endpoint { // eslint- if (reply == null) { throw new ApiError(meta.errors.noSuchReplyTarget); - } else if (isPureRenote(reply)) { + } else if (isRenote(reply) && !isQuote(reply)) { throw new ApiError(meta.errors.cannotReplyToPureRenote); } else if (!await this.noteEntityService.isVisibleForMe(reply, me.id)) { throw new ApiError(meta.errors.cannotReplyToInvisibleNote); diff --git a/packages/backend/src/server/api/endpoints/notes/edit.ts b/packages/backend/src/server/api/endpoints/notes/edit.ts index 3caeda288b..835cbc14fa 100644 --- a/packages/backend/src/server/api/endpoints/notes/edit.ts +++ b/packages/backend/src/server/api/endpoints/notes/edit.ts @@ -11,7 +11,7 @@ import { Endpoint } from '@/server/api/endpoint-base.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { NoteEditService } from '@/core/NoteEditService.js'; import { DI } from '@/di-symbols.js'; -import { isPureRenote } from '@/misc/is-pure-renote.js'; +import { isQuote, isRenote } from '@/misc/is-renote.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; import { ApiError } from '../../error.js'; @@ -336,7 +336,7 @@ export default class extends Endpoint { // eslint- if (renote == null) { throw new ApiError(meta.errors.noSuchRenoteTarget); - } else if (isPureRenote(renote)) { + } else if (isRenote(renote) && !isQuote(renote)) { throw new ApiError(meta.errors.cannotReRenote); } @@ -386,7 +386,7 @@ export default class extends Endpoint { // eslint- if (reply == null) { throw new ApiError(meta.errors.noSuchReplyTarget); - } else if (isPureRenote(reply)) { + } else if (isRenote(reply) && !isQuote(reply)) { throw new ApiError(meta.errors.cannotReplyToPureRenote); } else if (!await this.noteEntityService.isVisibleForMe(reply, me.id)) { throw new ApiError(meta.errors.cannotReplyToInvisibleNote); diff --git a/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts b/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts index ba38573065..4fd6f8682d 100644 --- a/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts +++ b/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts @@ -32,6 +32,7 @@ export const paramDef = { properties: { limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, offset: { type: 'integer', default: 0 }, + excludeChannels: { type: 'boolean', default: false }, }, required: [], } as const; @@ -86,6 +87,12 @@ export default class extends Endpoint { // eslint- query.setParameters(mutingQuery.getParameters()); //#endregion + //#region exclude channels + if (ps.excludeChannels) { + query.andWhere('poll.channelId IS NULL'); + } + //#endregion + const polls = await query .orderBy('poll.noteId', 'DESC') .limit(ps.limit) diff --git a/packages/backend/src/server/api/endpoints/notes/reactions.ts b/packages/backend/src/server/api/endpoints/notes/reactions.ts index 3beb5064ae..7e334df93e 100644 --- a/packages/backend/src/server/api/endpoints/notes/reactions.ts +++ b/packages/backend/src/server/api/endpoints/notes/reactions.ts @@ -79,7 +79,7 @@ export default class extends Endpoint { // eslint- const reactions = await query.limit(ps.limit).getMany(); - return await Promise.all(reactions.map(reaction => this.noteReactionEntityService.pack(reaction, me))); + return await this.noteReactionEntityService.packMany(reactions, me); }); } } diff --git a/packages/backend/src/server/api/endpoints/notes/translate.ts b/packages/backend/src/server/api/endpoints/notes/translate.ts index a935f761b7..d6ef655291 100644 --- a/packages/backend/src/server/api/endpoints/notes/translate.ts +++ b/packages/backend/src/server/api/endpoints/notes/translate.ts @@ -21,7 +21,7 @@ export const meta = { res: { type: 'object', - optional: false, nullable: false, + optional: true, nullable: false, properties: { sourceLang: { type: 'string' }, text: { type: 'string' }, @@ -39,6 +39,11 @@ export const meta = { code: 'NO_SUCH_NOTE', id: 'bea9b03f-36e0-49c5-a4db-627a029f8971', }, + cannotTranslateInvisibleNote: { + message: 'Cannot translate invisible note.', + code: 'CANNOT_TRANSLATE_INVISIBLE_NOTE', + id: 'ea29f2ca-c368-43b3-aaf1-5ac3e74bbe5d', + }, }, } as const; @@ -72,21 +77,21 @@ export default class extends Endpoint { // eslint- }); if (!(await this.noteEntityService.isVisibleForMe(note, me.id))) { - return 204; // TODO: 良い感じのエラー返す + throw new ApiError(meta.errors.cannotTranslateInvisibleNote); } if (note.text == null) { - return 204; + return; } const instance = await this.metaService.fetch(); if (instance.deeplAuthKey == null && !instance.deeplFreeMode) { - return 204; // TODO: 良い感じのエラー返す + throw new ApiError(meta.errors.unavailable); } if (instance.deeplFreeMode && !instance.deeplFreeInstance) { - return 204; + throw new ApiError(meta.errors.unavailable); } let targetLang = ps.targetLang; diff --git a/packages/backend/src/server/api/endpoints/roles/users.ts b/packages/backend/src/server/api/endpoints/roles/users.ts index 85d100ce1c..48d350af59 100644 --- a/packages/backend/src/server/api/endpoints/roles/users.ts +++ b/packages/backend/src/server/api/endpoints/roles/users.ts @@ -92,9 +92,12 @@ export default class extends Endpoint { // eslint- .limit(ps.limit) .getMany(); + const _users = assigns.map(({ user, userId }) => user ?? userId); + const _userMap = await this.userEntityService.packMany(_users, me, { schema: 'UserDetailed' }) + .then(users => new Map(users.map(u => [u.id, u]))); return await Promise.all(assigns.map(async assign => ({ id: assign.id, - user: await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }), + user: _userMap.get(assign.userId) ?? await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }), }))); }); } diff --git a/packages/backend/src/server/api/endpoints/sponsors.ts b/packages/backend/src/server/api/endpoints/sponsors.ts index 50e1c594f2..b6ccb9b2f9 100644 --- a/packages/backend/src/server/api/endpoints/sponsors.ts +++ b/packages/backend/src/server/api/endpoints/sponsors.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import * as Redis from 'ioredis'; import { Endpoint } from '@/server/api/endpoint-base.js'; diff --git a/packages/backend/src/server/api/endpoints/users/following.ts b/packages/backend/src/server/api/endpoints/users/following.ts index 5d52ebba76..6b3389f0b2 100644 --- a/packages/backend/src/server/api/endpoints/users/following.ts +++ b/packages/backend/src/server/api/endpoints/users/following.ts @@ -6,6 +6,7 @@ import { IsNull } from 'typeorm'; import { Inject, Injectable } from '@nestjs/common'; import type { UsersRepository, FollowingsRepository, UserProfilesRepository } from '@/models/_.js'; +import { birthdaySchema } from '@/models/User.js'; import { Endpoint } from '@/server/api/endpoint-base.js'; import { QueryService } from '@/core/QueryService.js'; import { FollowingEntityService } from '@/core/entities/FollowingEntityService.js'; @@ -66,7 +67,7 @@ export const paramDef = { description: 'The local host is represented with `null`.', }, - birthday: { type: 'string', nullable: true }, + birthday: { ...birthdaySchema, nullable: true }, }, anyOf: [ { required: ['userId'] }, @@ -127,9 +128,7 @@ export default class extends Endpoint { // eslint- if (ps.birthday) { try { - const d = new Date(ps.birthday); - d.setHours(0, 0, 0, 0); - const birthday = `${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; + const birthday = ps.birthday.substring(5, 10); const birthdayUserQuery = this.userProfilesRepository.createQueryBuilder('user_profile'); birthdayUserQuery.select('user_profile.userId') .where(`SUBSTR(user_profile.birthday, 6, 5) = '${birthday}'`); diff --git a/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts b/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts index 02aa037466..9248a2fa68 100644 --- a/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts +++ b/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts @@ -118,12 +118,14 @@ export default class extends Endpoint { // eslint- const repliedUsersSorted = Object.keys(repliedUsers).sort((a, b) => repliedUsers[b] - repliedUsers[a]); // Extract top replied users - const topRepliedUsers = repliedUsersSorted.slice(0, ps.limit); + const topRepliedUserIds = repliedUsersSorted.slice(0, ps.limit); // Make replies object (includes weights) - const repliesObj = await Promise.all(topRepliedUsers.map(async (user) => ({ - user: await this.userEntityService.pack(user, me, { schema: 'UserDetailed' }), - weight: repliedUsers[user] / peak, + const _userMap = await this.userEntityService.packMany(topRepliedUserIds, me, { schema: 'UserDetailed' }) + .then(users => new Map(users.map(u => [u.id, u]))); + const repliesObj = await Promise.all(topRepliedUserIds.map(async (userId) => ({ + user: _userMap.get(userId) ?? await this.userEntityService.pack(userId, me, { schema: 'UserDetailed' }), + weight: repliedUsers[userId] / peak, }))); return repliesObj; diff --git a/packages/backend/src/server/api/endpoints/users/relation.ts b/packages/backend/src/server/api/endpoints/users/relation.ts index 6a5b2262fa..1d75437b81 100644 --- a/packages/backend/src/server/api/endpoints/users/relation.ts +++ b/packages/backend/src/server/api/endpoints/users/relation.ts @@ -132,11 +132,9 @@ export default class extends Endpoint { // eslint- private userEntityService: UserEntityService, ) { super(meta, paramDef, async (ps, me) => { - const ids = Array.isArray(ps.userId) ? ps.userId : [ps.userId]; - - const relations = await Promise.all(ids.map(id => this.userEntityService.getRelation(me.id, id))); - - return Array.isArray(ps.userId) ? relations : relations[0]; + return Array.isArray(ps.userId) + ? await this.userEntityService.getRelations(me.id, ps.userId).then(it => [...it.values()]) + : await this.userEntityService.getRelation(me.id, ps.userId).then(it => [it]); }); } } diff --git a/packages/backend/src/server/api/endpoints/users/show.ts b/packages/backend/src/server/api/endpoints/users/show.ts index bd81989cb9..062326e28d 100644 --- a/packages/backend/src/server/api/endpoints/users/show.ts +++ b/packages/backend/src/server/api/endpoints/users/show.ts @@ -110,14 +110,16 @@ export default class extends Endpoint { // eslint- }); // リクエストされた通りに並べ替え + // 順番は保持されるけど数は減ってる可能性がある const _users: MiUser[] = []; for (const id of ps.userIds) { - _users.push(users.find(x => x.id === id)!); + const user = users.find(x => x.id === id); + if (user != null) _users.push(user); } - return await Promise.all(_users.map(u => this.userEntityService.pack(u, me, { - schema: 'UserDetailed', - }))); + const _userMap = await this.userEntityService.packMany(_users, me, { schema: 'UserDetailed' }) + .then(users => new Map(users.map(u => [u.id, u]))); + return _users.map(u => _userMap.get(u.id)!); } else { // Lookup user if (typeof ps.host === 'string' && typeof ps.username === 'string') { diff --git a/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts b/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts index 5706a17786..8c9cca1730 100644 --- a/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts +++ b/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import megalodon, { Entity, MegalodonInterface } from 'megalodon'; import querystring from 'querystring'; @@ -89,7 +94,7 @@ export class MastodonApiServerService { reply.code(401).send(e.response.data); } }); - + fastify.get('/v1/instance', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -113,7 +118,7 @@ export class MastodonApiServerService { reply.code(401).send(e.response.data); } }); - + fastify.get('/v1/announcements', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -126,7 +131,7 @@ export class MastodonApiServerService { reply.code(401).send(e.response.data); } }); - + fastify.post<{ Body: { id: string } }>('/v1/announcements/:id/dismiss', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -177,8 +182,8 @@ export class MastodonApiServerService { /* console.error(e); */ reply.code(401).send(e.response.data); } - }); - + }); + fastify.get('/v1/filters', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -192,7 +197,7 @@ export class MastodonApiServerService { reply.code(401).send(e.response.data); } }); - + fastify.get('/v1/trends', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -238,7 +243,7 @@ export class MastodonApiServerService { reply.code(401).send(e.response.data); } }); - + fastify.get('/v1/preferences', async (_request, reply) => { const BASE_URL = `${_request.protocol}://${_request.hostname}`; const accessTokens = _request.headers.authorization; @@ -291,18 +296,18 @@ export class MastodonApiServerService { user: { id: tokeninfo.userId, host: null }, path: avatar.path, name: avatar.originalname !== null && avatar.originalname !== 'file' ? avatar.originalname : undefined, - sensitive: false, + sensitive: false, }); if (upload.type.startsWith('image/')) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (_request.body as any).avatar = upload.id; } - } else if (tokeninfo && header) { + } else if (tokeninfo && header) { const upload = await this.driveService.addFile({ user: { id: tokeninfo.userId, host: null }, path: header.path, name: header.originalname !== null && header.originalname !== 'file' ? header.originalname : undefined, - sensitive: false, + sensitive: false, }); if (upload.type.startsWith('image/')) { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -324,7 +329,7 @@ export class MastodonApiServerService { }; }); // eslint-disable-next-line @typescript-eslint/no-explicit-any - (_request.body as any).fields_attributes = fields.filter((field: any) => field.name.trim().length > 0 && field.value.length > 0); + (_request.body as any).fields_attributes = fields.filter((field: any) => field.name.trim().length > 0 && field.value.length > 0); } const data = await client.updateCredentials(_request.body!); diff --git a/packages/backend/src/server/api/mastodon/converters.ts b/packages/backend/src/server/api/mastodon/converters.ts index cca9505846..405701e826 100644 --- a/packages/backend/src/server/api/mastodon/converters.ts +++ b/packages/backend/src/server/api/mastodon/converters.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Inject, Injectable } from '@nestjs/common'; import { Entity } from 'megalodon'; import mfm from '@transfem-org/sfm-js'; diff --git a/packages/backend/src/server/api/mastodon/endpoints.ts b/packages/backend/src/server/api/mastodon/endpoints.ts index 5a75823891..085314059b 100644 --- a/packages/backend/src/server/api/mastodon/endpoints.ts +++ b/packages/backend/src/server/api/mastodon/endpoints.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { ApiAuthMastodon } from './endpoints/auth.js'; import { ApiAccountMastodon } from './endpoints/account.js'; import { ApiSearchMastodon } from './endpoints/search.js'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/account.ts b/packages/backend/src/server/api/mastodon/endpoints/account.ts index 07d9efb8c1..6fcfb0019c 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/account.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/account.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { MastoConverters, convertRelationship } from '../converters.js'; import { argsToBools, limitToInt } from './timeline.js'; import type { MegalodonInterface } from 'megalodon'; @@ -104,7 +109,7 @@ export class ApiAccountMastodon { public async getFollowers() { try { const data = await this.client.getAccountFollowers( - (this.request.params as any).id, + (this.request.params as any).id, limitToInt(this.request.query as any), ); return await Promise.all(data.data.map(async (account) => await this.mastoconverter.convertAccount(account))); @@ -118,7 +123,7 @@ export class ApiAccountMastodon { public async getFollowing() { try { const data = await this.client.getAccountFollowing( - (this.request.params as any).id, + (this.request.params as any).id, limitToInt(this.request.query as any), ); return await Promise.all(data.data.map(async (account) => await this.mastoconverter.convertAccount(account))); diff --git a/packages/backend/src/server/api/mastodon/endpoints/auth.ts b/packages/backend/src/server/api/mastodon/endpoints/auth.ts index 80a5e89ca3..a447bdb1b7 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/auth.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/auth.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import type { MegalodonInterface } from 'megalodon'; import type { FastifyRequest } from 'fastify'; @@ -65,7 +70,7 @@ export async function ApiAuthMastodon(request: FastifyRequest, client: Megalodon client_id: Buffer.from(appData.url || '').toString('base64'), client_secret: appData.clientSecret, }; - + return returns; } catch (e: any) { console.error(e); diff --git a/packages/backend/src/server/api/mastodon/endpoints/filter.ts b/packages/backend/src/server/api/mastodon/endpoints/filter.ts index 212c79b251..ce6809d230 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/filter.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/filter.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { convertFilter } from '../converters.js'; import type { MegalodonInterface } from 'megalodon'; import type { FastifyRequest } from 'fastify'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/meta.ts b/packages/backend/src/server/api/mastodon/endpoints/meta.ts index efb39ef939..79d2c62a24 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/meta.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/meta.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { Entity } from 'megalodon'; import { FILE_TYPE_BROWSERSAFE } from '@/const.js'; import type { Config } from '@/config.js'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/notifications.ts b/packages/backend/src/server/api/mastodon/endpoints/notifications.ts index c4628b58c4..0eefb5894c 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/notifications.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/notifications.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { convertNotification } from '../converters.js'; import type { MegalodonInterface, Entity } from 'megalodon'; import type { FastifyRequest } from 'fastify'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/search.ts b/packages/backend/src/server/api/mastodon/endpoints/search.ts index 500129c901..946e796e2a 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/search.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/search.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { MastoConverters } from '../converters.js'; import { limitToInt } from './timeline.js'; import type { MegalodonInterface } from 'megalodon'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/status.ts b/packages/backend/src/server/api/mastodon/endpoints/status.ts index fe77646af4..ddc99639fa 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/status.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/status.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import querystring from 'querystring'; import { emojiRegexAtStartToEnd } from '@/misc/emoji-regex.js'; import { convertAttachment, convertPoll, convertStatusSource, MastoConverters } from '../converters.js'; diff --git a/packages/backend/src/server/api/mastodon/endpoints/timeline.ts b/packages/backend/src/server/api/mastodon/endpoints/timeline.ts index f81b63b9ac..3eb4898713 100644 --- a/packages/backend/src/server/api/mastodon/endpoints/timeline.ts +++ b/packages/backend/src/server/api/mastodon/endpoints/timeline.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: marie and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { ParsedUrlQuery } from 'querystring'; import { convertConversation, convertList, MastoConverters } from '../converters.js'; import { getClient } from '../MastodonApiServerService.js'; diff --git a/packages/backend/src/server/api/openapi/gen-spec.ts b/packages/backend/src/server/api/openapi/gen-spec.ts index b5f91ff542..436f9a44bb 100644 --- a/packages/backend/src/server/api/openapi/gen-spec.ts +++ b/packages/backend/src/server/api/openapi/gen-spec.ts @@ -93,7 +93,7 @@ export function genOpenapiSpec(config: Config, includeSelfRef = false) { const hasBody = (schema.type === 'object' && schema.properties && Object.keys(schema.properties).length >= 1); const info = { - operationId: endpoint.name, + operationId: endpoint.name.replaceAll('/', '___'), // NOTE: スラッシュは使えない summary: endpoint.name, description: desc, externalDocs: { diff --git a/packages/backend/src/server/api/stream/channel.ts b/packages/backend/src/server/api/stream/channel.ts index 44a143538b..49b0ae1d5b 100644 --- a/packages/backend/src/server/api/stream/channel.ts +++ b/packages/backend/src/server/api/stream/channel.ts @@ -4,6 +4,10 @@ */ import { bindThis } from '@/decorators.js'; +import { isInstanceMuted } from '@/misc/is-instance-muted.js'; +import { isUserRelated } from '@/misc/is-user-related.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; +import type { Packed } from '@/misc/json-schema.js'; import type Connection from './Connection.js'; /** @@ -54,6 +58,24 @@ export default abstract class Channel { return this.connection.subscriber; } + /* + * ミュートとブロックされてるを処理する + */ + protected isNoteMutedOrBlocked(note: Packed<'Note'>): boolean { + // 流れてきたNoteがインスタンスミュートしたインスタンスが関わる + if (isInstanceMuted(note, new Set(this.userProfile?.mutedInstances ?? [])) && !this.following[note.userId]) return true; + + // 流れてきたNoteがミュートしているユーザーが関わる + if (isUserRelated(note, this.userIdsWhoMeMuting)) return true; + // 流れてきたNoteがブロックされているユーザーが関わる + if (isUserRelated(note, this.userIdsWhoBlockingMe)) return true; + + // 流れてきたNoteがリノートをミュートしてるユーザが行ったもの + if (isRenotePacked(note) && !isQuotePacked(note) && this.userIdsWhoMeMutingRenotes.has(note.user.id)) return true; + + return false; + } + constructor(id: string, connection: Connection) { this.id = id; this.connection = connection; diff --git a/packages/backend/src/server/api/stream/channels/antenna.ts b/packages/backend/src/server/api/stream/channels/antenna.ts index 135d162e63..4a1d2dd109 100644 --- a/packages/backend/src/server/api/stream/channels/antenna.ts +++ b/packages/backend/src/server/api/stream/channels/antenna.ts @@ -4,7 +4,6 @@ */ import { Injectable } from '@nestjs/common'; -import { isUserRelated } from '@/misc/is-user-related.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import type { GlobalEvents } from '@/core/GlobalEventService.js'; @@ -40,12 +39,7 @@ class AntennaChannel extends Channel { if (data.type === 'note') { const note = await this.noteEntityService.pack(data.body.id, this.user, { detail: true }); - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; + if (this.isNoteMutedOrBlocked(note)) return; this.connection.cacheNote(note); diff --git a/packages/backend/src/server/api/stream/channels/bubble-timeline.ts b/packages/backend/src/server/api/stream/channels/bubble-timeline.ts index 2d85d65ba5..01be2d2089 100644 --- a/packages/backend/src/server/api/stream/channels/bubble-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/bubble-timeline.ts @@ -4,15 +4,13 @@ */ import { Injectable } from '@nestjs/common'; -import { checkWordMute } from '@/misc/check-word-mute.js'; -import { isInstanceMuted } from '@/misc/is-instance-muted.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; import type { MiMeta } from '@/models/Meta.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { MiChannelService } from '../channel.js'; class BubbleTimelineChannel extends Channel { @@ -54,36 +52,18 @@ class BubbleTimelineChannel extends Channel { private async onNote(note: Packed<'Note'>) { if (this.withFiles && (note.fileIds == null || note.fileIds.length === 0)) return; if (!this.withBots && note.user.isBot) return; - + if (!(note.user.host != null && this.instance.bubbleInstances.includes(note.user.host) && note.visibility === 'public' )) return; if (note.channelId != null) return; - // 関係ない返信は除外 - if (note.reply && !this.following[note.userId]?.withReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if (reply.userId !== this.user!.id && note.userId !== this.user!.id && reply.userId !== note.userId) return; - } + if (isRenotePacked(note) && !isQuotePacked(note) && !this.withRenotes) return; if (note.user.isSilenced && !this.following[note.userId] && note.userId !== this.user!.id) return; - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; + if (this.isNoteMutedOrBlocked(note)) return; - // Ignore notes from instances the user has muted - if (isInstanceMuted(note, new Set(this.userProfile?.mutedInstances ?? [])) && !this.following[note.userId]) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; - - if (note.renote && !note.text && note.renote.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - if (note.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/channel.ts b/packages/backend/src/server/api/stream/channels/channel.ts index 61bb4bfae2..865e4fed19 100644 --- a/packages/backend/src/server/api/stream/channels/channel.ts +++ b/packages/backend/src/server/api/stream/channels/channel.ts @@ -4,10 +4,10 @@ */ import { Injectable } from '@nestjs/common'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class ChannelChannel extends Channel { @@ -46,14 +46,9 @@ class ChannelChannel extends Channel { if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; + if (this.isNoteMutedOrBlocked(note)) return; - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/global-timeline.ts b/packages/backend/src/server/api/stream/channels/global-timeline.ts index fc25724782..0a894147a2 100644 --- a/packages/backend/src/server/api/stream/channels/global-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/global-timeline.ts @@ -4,14 +4,12 @@ */ import { Injectable } from '@nestjs/common'; -import { checkWordMute } from '@/misc/check-word-mute.js'; -import { isInstanceMuted } from '@/misc/is-instance-muted.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class GlobalTimelineChannel extends Channel { @@ -55,31 +53,13 @@ class GlobalTimelineChannel extends Channel { if (note.visibility !== 'public') return; if (note.channelId != null) return; - // 関係ない返信は除外 - if (note.reply && !this.following[note.userId]?.withReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if (reply.userId !== this.user!.id && note.userId !== this.user!.id && reply.userId !== note.userId) return; - } + if (isRenotePacked(note) && !isQuotePacked(note) && !this.withRenotes) return; if (note.user.isSilenced && !this.following[note.userId] && note.userId !== this.user!.id) return; - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; + if (this.isNoteMutedOrBlocked(note)) return; - // Ignore notes from instances the user has muted - if (isInstanceMuted(note, new Set(this.userProfile?.mutedInstances ?? [])) && !this.following[note.userId]) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; - - if (note.renote && !note.text && note.renote.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - if (note.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/hashtag.ts b/packages/backend/src/server/api/stream/channels/hashtag.ts index 377b1a0162..57bada5d9c 100644 --- a/packages/backend/src/server/api/stream/channels/hashtag.ts +++ b/packages/backend/src/server/api/stream/channels/hashtag.ts @@ -5,10 +5,10 @@ import { Injectable } from '@nestjs/common'; import { normalizeForSearch } from '@/misc/normalize-for-search.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class HashtagChannel extends Channel { @@ -43,14 +43,9 @@ class HashtagChannel extends Channel { const matched = this.q.some(tags => tags.every(tag => noteTags.includes(normalizeForSearch(tag)))); if (!matched) return; - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; + if (this.isNoteMutedOrBlocked(note)) return; - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/home-timeline.ts b/packages/backend/src/server/api/stream/channels/home-timeline.ts index 0a4852ee8d..84ff241469 100644 --- a/packages/backend/src/server/api/stream/channels/home-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/home-timeline.ts @@ -4,12 +4,10 @@ */ import { Injectable } from '@nestjs/common'; -import { checkWordMute } from '@/misc/check-word-mute.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; -import { isInstanceMuted } from '@/misc/is-instance-muted.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class HomeTimelineChannel extends Channel { @@ -51,9 +49,6 @@ class HomeTimelineChannel extends Channel { if (!isMe && !Object.hasOwn(this.following, note.userId)) return; } - // Ignore notes from instances the user has muted - if (isInstanceMuted(note, new Set(this.userProfile!.mutedInstances)) && !this.following[note.userId]) return; - if (note.visibility === 'followers') { if (!isMe && !Object.hasOwn(this.following, note.userId)) return; } else if (note.visibility === 'specified') { @@ -74,7 +69,7 @@ class HomeTimelineChannel extends Channel { if (note.user.isSilenced && !this.following[note.userId] && note.userId !== this.user!.id) return; // 純粋なリノート(引用リノートでないリノート)の場合 - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && note.poll == null) { + if (isRenotePacked(note) && !isQuotePacked(note) && note.renote) { if (!this.withRenotes) return; if (note.renote.reply) { const reply = note.renote.reply; @@ -83,17 +78,9 @@ class HomeTimelineChannel extends Channel { } } - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; + if (this.isNoteMutedOrBlocked(note)) return; - if (note.renote && !note.text && note.renote.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - if (note.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts b/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts index 02786e9e16..b83d3ec817 100644 --- a/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts @@ -4,14 +4,12 @@ */ import { Injectable } from '@nestjs/common'; -import { checkWordMute } from '@/misc/check-word-mute.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; -import { isInstanceMuted } from '@/misc/is-instance-muted.js'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class HybridTimelineChannel extends Channel { @@ -74,8 +72,7 @@ class HybridTimelineChannel extends Channel { if (!isMe && !note.visibleUserIds!.includes(this.user!.id)) return; } - // Ignore notes from instances the user has muted - if (isInstanceMuted(note, new Set(this.userProfile!.mutedInstances)) && !this.following[note.userId]) return; + if (this.isNoteMutedOrBlocked(note)) return; if (note.reply) { const reply = note.reply; @@ -90,17 +87,7 @@ class HybridTimelineChannel extends Channel { if (note.user.isSilenced && !this.following[note.userId] && note.userId !== this.user!.id) return; - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; - - if (note.renote && !note.text && note.renote.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - if (note.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; + if (isRenotePacked(note) && !isQuotePacked(note) && !this.withRenotes) return; if (this.user && note.renoteId && !note.text) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { diff --git a/packages/backend/src/server/api/stream/channels/local-timeline.ts b/packages/backend/src/server/api/stream/channels/local-timeline.ts index 71b5675402..48cc76c497 100644 --- a/packages/backend/src/server/api/stream/channels/local-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/local-timeline.ts @@ -4,13 +4,12 @@ */ import { Injectable } from '@nestjs/common'; -import { checkWordMute } from '@/misc/check-word-mute.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; +import { isQuotePacked, isRenotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class LocalTimelineChannel extends Channel { @@ -66,19 +65,11 @@ class LocalTimelineChannel extends Channel { if (note.user.isSilenced && !this.following[note.userId] && note.userId !== this.user!.id) return; - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; + if (isRenotePacked(note) && !isQuotePacked(note) && !this.withRenotes) return; - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; + if (this.isNoteMutedOrBlocked(note)) return; - if (note.renote && !note.text && note.renote.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - if (note.mentions?.some(mention => this.userIdsWhoMeMuting.has(mention))) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; diff --git a/packages/backend/src/server/api/stream/channels/role-timeline.ts b/packages/backend/src/server/api/stream/channels/role-timeline.ts index 80aab4b35e..6a4ad22460 100644 --- a/packages/backend/src/server/api/stream/channels/role-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/role-timeline.ts @@ -4,8 +4,6 @@ */ import { Injectable } from '@nestjs/common'; -import { isUserRelated } from '@/misc/is-user-related.js'; -import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; @@ -46,12 +44,7 @@ class RoleTimelineChannel extends Channel { } if (note.visibility !== 'public') return; - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; - - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; + if (this.isNoteMutedOrBlocked(note)) return; this.send('note', note); } else { diff --git a/packages/backend/src/server/api/stream/channels/user-list.ts b/packages/backend/src/server/api/stream/channels/user-list.ts index f7bb106c03..14b30a157c 100644 --- a/packages/backend/src/server/api/stream/channels/user-list.ts +++ b/packages/backend/src/server/api/stream/channels/user-list.ts @@ -5,12 +5,11 @@ import { Inject, Injectable } from '@nestjs/common'; import type { MiUserListMembership, UserListMembershipsRepository, UserListsRepository } from '@/models/_.js'; -import { isUserRelated } from '@/misc/is-user-related.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { DI } from '@/di-symbols.js'; import { bindThis } from '@/decorators.js'; -import { isInstanceMuted } from '@/misc/is-instance-muted.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import Channel, { type MiChannelService } from '../channel.js'; class UserListChannel extends Channel { @@ -106,25 +105,17 @@ class UserListChannel extends Channel { } } - if (note.renote && note.text == null && (note.fileIds == null || note.fileIds.length === 0) && !this.withRenotes) return; + if (isRenotePacked(note) && !isQuotePacked(note) && !this.withRenotes) return; - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoMeMuting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.userIdsWhoBlockingMe)) return; + if (this.isNoteMutedOrBlocked(note)) return; - if (note.renote && !note.text && isUserRelated(note, this.userIdsWhoMeMutingRenotes)) return; - - if (this.user && note.renoteId && !note.text) { + if (this.user && isRenotePacked(note) && !isQuotePacked(note)) { if (note.renote && Object.keys(note.renote.reactions).length > 0) { const myRenoteReaction = await this.noteEntityService.populateMyReaction(note.renote, this.user.id); note.renote.myReaction = myRenoteReaction; } } - // 流れてきたNoteがミュートしているインスタンスに関わるものだったら無視する - if (isInstanceMuted(note, this.userMutedInstances)) return; - this.connection.cacheNote(note); this.send('note', note); diff --git a/packages/backend/src/server/web/ClientServerService.ts b/packages/backend/src/server/web/ClientServerService.ts index cb41c4f338..702e306feb 100644 --- a/packages/backend/src/server/web/ClientServerService.ts +++ b/packages/backend/src/server/web/ClientServerService.ts @@ -202,9 +202,18 @@ export class ClientServerService { // Authenticate fastify.addHook('onRequest', async (request, reply) => { + if (request.routeOptions.url == null) { + reply.code(404).send('Not found'); + return; + } + // %71ueueとかでリクエストされたら困るため const url = decodeURI(request.routeOptions.url); if (url === bullBoardPath || url.startsWith(bullBoardPath + '/')) { + if (!url.startsWith(bullBoardPath + '/static/')) { + reply.header('Cache-Control', 'private, max-age=0, must-revalidate'); + } + const token = request.cookies.token; if (token == null) { reply.code(401).send('Login required'); @@ -447,7 +456,7 @@ export class ClientServerService { //#endregion - const renderBase = async (reply: FastifyReply) => { + const renderBase = async (reply: FastifyReply, data: { [key: string]: any } = {}) => { const meta = await this.metaService.fetch(); reply.header('Cache-Control', 'public, max-age=30'); return await reply.view('base', { @@ -456,6 +465,7 @@ export class ClientServerService { title: meta.name ?? 'Misskey', desc: meta.description, ...await this.generateCommonPugData(meta), + ...data, }); }; @@ -474,7 +484,9 @@ export class ClientServerService { }; // Atom - fastify.get<{ Params: { user: string; } }>('/@:user.atom', async (request, reply) => { + fastify.get<{ Params: { user?: string; } }>('/@:user.atom', async (request, reply) => { + if (request.params.user == null) return await renderBase(reply); + const feed = await getFeed(request.params.user); if (feed) { @@ -487,7 +499,9 @@ export class ClientServerService { }); // RSS - fastify.get<{ Params: { user: string; } }>('/@:user.rss', async (request, reply) => { + fastify.get<{ Params: { user?: string; } }>('/@:user.rss', async (request, reply) => { + if (request.params.user == null) return await renderBase(reply); + const feed = await getFeed(request.params.user); if (feed) { @@ -500,7 +514,9 @@ export class ClientServerService { }); // JSON - fastify.get<{ Params: { user: string; } }>('/@:user.json', async (request, reply) => { + fastify.get<{ Params: { user?: string; } }>('/@:user.json', async (request, reply) => { + if (request.params.user == null) return await renderBase(reply); + const feed = await getFeed(request.params.user); if (feed) { @@ -753,6 +769,18 @@ export class ClientServerService { }); //#endregion + //region noindex pages + // Tags + fastify.get<{ Params: { clip: string; } }>('/tags/:tag', async (request, reply) => { + return await renderBase(reply, { noindex: true }); + }); + + // User with Tags + fastify.get<{ Params: { clip: string; } }>('/user-tags/:tag', async (request, reply) => { + return await renderBase(reply, { noindex: true }); + }); + //endregion + fastify.get('/_info_card_', async (request, reply) => { const meta = await this.metaService.fetch(true); diff --git a/packages/backend/src/server/web/UrlPreviewService.ts b/packages/backend/src/server/web/UrlPreviewService.ts index c6a96e94cb..8f8f08a305 100644 --- a/packages/backend/src/server/web/UrlPreviewService.ts +++ b/packages/backend/src/server/web/UrlPreviewService.ts @@ -5,6 +5,7 @@ import { Inject, Injectable } from '@nestjs/common'; import { summaly } from '@misskey-dev/summaly'; +import { SummalyResult } from '@misskey-dev/summaly/built/summary.js'; import { DI } from '@/di-symbols.js'; import type { Config } from '@/config.js'; import { MetaService } from '@/core/MetaService.js'; @@ -14,6 +15,7 @@ import { query } from '@/misc/prelude/url.js'; import { LoggerService } from '@/core/LoggerService.js'; import { bindThis } from '@/decorators.js'; import { ApiError } from '@/server/api/error.js'; +import { MiMeta } from '@/models/Meta.js'; import type { FastifyRequest, FastifyReply } from 'fastify'; @Injectable() @@ -62,24 +64,25 @@ export class UrlPreviewService { const meta = await this.metaService.fetch(); - this.logger.info(meta.summalyProxy + if (!meta.urlPreviewEnabled) { + reply.code(403); + return { + error: new ApiError({ + message: 'URL preview is disabled', + code: 'URL_PREVIEW_DISABLED', + id: '58b36e13-d2f5-0323-b0c6-76aa9dabefb8', + }), + }; + } + + this.logger.info(meta.urlPreviewSummaryProxyUrl ? `(Proxy) Getting preview of ${url}@${lang} ...` : `Getting preview of ${url}@${lang} ...`); + try { - const summary = meta.summalyProxy ? - await this.httpRequestService.getJson>(`${meta.summalyProxy}?${query({ - url: url, - lang: lang ?? 'ja-JP', - })}`) - : - await summaly(url, { - followRedirects: false, - lang: lang ?? 'ja-JP', - agent: this.config.proxy ? { - http: this.httpRequestService.httpAgent, - https: this.httpRequestService.httpsAgent, - } : undefined, - }); + const summary = meta.urlPreviewSummaryProxyUrl + ? await this.fetchSummaryFromProxy(url, meta, lang) + : await this.fetchSummary(url, meta, lang); this.logger.succ(`Got preview of ${url}: ${summary.title}`); @@ -100,6 +103,7 @@ export class UrlPreviewService { return summary; } catch (err) { this.logger.warn(`Failed to get preview of ${url}: ${err}`); + reply.code(422); reply.header('Cache-Control', 'max-age=86400, immutable'); return { @@ -111,4 +115,37 @@ export class UrlPreviewService { }; } } + + private fetchSummary(url: string, meta: MiMeta, lang?: string): Promise { + const agent = this.config.proxy + ? { + http: this.httpRequestService.httpAgent, + https: this.httpRequestService.httpsAgent, + } + : undefined; + + return summaly(url, { + followRedirects: false, + lang: lang ?? 'ja-JP', + agent: agent, + userAgent: meta.urlPreviewUserAgent ?? undefined, + operationTimeout: meta.urlPreviewTimeout, + contentLengthLimit: meta.urlPreviewMaximumContentLength, + contentLengthRequired: meta.urlPreviewRequireContentLength, + }); + } + + private fetchSummaryFromProxy(url: string, meta: MiMeta, lang?: string): Promise { + const proxy = meta.urlPreviewSummaryProxyUrl!; + const queryStr = query({ + url: url, + lang: lang ?? 'ja-JP', + userAgent: meta.urlPreviewUserAgent ?? undefined, + operationTimeout: meta.urlPreviewTimeout, + contentLengthLimit: meta.urlPreviewMaximumContentLength, + contentLengthRequired: meta.urlPreviewRequireContentLength, + }); + + return this.httpRequestService.getJson(`${proxy}?${queryStr}`); + } } diff --git a/packages/backend/src/server/web/boot.js b/packages/backend/src/server/web/boot.js index 6b9dc0a103..0543cc2b65 100644 --- a/packages/backend/src/server/web/boot.js +++ b/packages/backend/src/server/web/boot.js @@ -86,8 +86,8 @@ //#endregion //#region Script - function importAppScript() { - import(`/vite/${CLIENT_ENTRY}`) + async function importAppScript() { + await import(`/vite/${CLIENT_ENTRY}`) .catch(async e => { console.error(e); renderError('APP_IMPORT', e); diff --git a/packages/backend/src/server/web/views/base.pug b/packages/backend/src/server/web/views/base.pug index 0f555e0637..c1e38717c8 100644 --- a/packages/backend/src/server/web/views/base.pug +++ b/packages/backend/src/server/web/views/base.pug @@ -55,6 +55,9 @@ html block title = title || 'Sharkey' + if noindex + meta(name='robots' content='noindex') + block desc meta(name='description' content= desc || '✨🌎✨ A interplanetary communication platform ✨🚀✨') diff --git a/packages/backend/src/server/web/views/note.pug b/packages/backend/src/server/web/views/note.pug index 47c89ae2d7..a7cd0293cd 100644 --- a/packages/backend/src/server/web/views/note.pug +++ b/packages/backend/src/server/web/views/note.pug @@ -2,7 +2,7 @@ extends ./base block vars - const user = note.user; - - const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`; + - const title = user.name ? `${user.name} (@${user.username}${user.host ? `@${user.host}` : ''})` : `@${user.username}${user.host ? `@${user.host}` : ''}`; - const url = `${config.url}/notes/${note.id}`; - const isRenote = note.renote && note.text == null && note.fileIds.length == 0 && note.poll == null; - const images = note.cw ? [] : (note.files || []).filter(file => file.type.startsWith('image/') && !file.isSensitive) @@ -28,7 +28,7 @@ block og // FIXME: add embed player for Twitter if images.length meta(property='twitter:card' content='summary_large_image') - each image in images + each image in images meta(property='og:image' content= image.url) else meta(property='twitter:card' content='summary') diff --git a/packages/backend/src/server/web/views/page.pug b/packages/backend/src/server/web/views/page.pug index 08bb08ffe7..03c50eca8a 100644 --- a/packages/backend/src/server/web/views/page.pug +++ b/packages/backend/src/server/web/views/page.pug @@ -3,7 +3,7 @@ extends ./base block vars - const user = page.user; - const title = page.title; - - const url = `${config.url}/@${user.username}/${page.name}`; + - const url = `${config.url}/@${user.username}/pages/${page.name}`; block title = `${title} | ${instanceName}` diff --git a/packages/backend/src/server/web/views/user.pug b/packages/backend/src/server/web/views/user.pug index 83d57349a6..2b0a7bab5c 100644 --- a/packages/backend/src/server/web/views/user.pug +++ b/packages/backend/src/server/web/views/user.pug @@ -1,7 +1,7 @@ extends ./base block vars - - const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`; + - const title = user.name ? `${user.name} (@${user.username}${user.host ? `@${user.host}` : ''})` : `@${user.username}${user.host ? `@${user.host}` : ''}`; - const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`; block title diff --git a/packages/backend/test/e2e/2fa.ts b/packages/backend/test/e2e/2fa.ts index 87a3c227d6..13c56b88a6 100644 --- a/packages/backend/test/e2e/2fa.ts +++ b/packages/backend/test/e2e/2fa.ts @@ -187,7 +187,7 @@ describe('2要素認証', () => { }, 1000 * 60 * 2); test('が設定でき、OTPでログインできる。', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); @@ -197,18 +197,18 @@ describe('2要素認証', () => { assert.strictEqual(registerResponse.body.label, username); assert.strictEqual(registerResponse.body.issuer, config.host); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const usersShowResponse = await api('/users/show', { + const usersShowResponse = await api('users/show', { username, }, alice); assert.strictEqual(usersShowResponse.status, 200); assert.strictEqual(usersShowResponse.body.twoFactorEnabled, true); - const signinResponse = await api('/signin', { + const signinResponse = await api('signin', { ...signinParam(), token: otpToken(registerResponse.body.secret), }); @@ -216,24 +216,24 @@ describe('2要素認証', () => { assert.notEqual(signinResponse.body.i, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); }); test('が設定でき、セキュリティキーでログインできる。', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const registerKeyResponse = await api('/i/2fa/register-key', { + const registerKeyResponse = await api('i/2fa/register-key', { password, token: otpToken(registerResponse.body.secret), }, alice); @@ -243,23 +243,23 @@ describe('2要素認証', () => { const keyName = 'example-key'; const credentialId = crypto.randomBytes(0x41); - const keyDoneResponse = await api('/i/2fa/key-done', keyDoneParam({ + const keyDoneResponse = await api('i/2fa/key-done', keyDoneParam({ token: otpToken(registerResponse.body.secret), keyName, credentialId, creationOptions: registerKeyResponse.body, - }), alice); + }) as any, alice); assert.strictEqual(keyDoneResponse.status, 200); assert.strictEqual(keyDoneResponse.body.id, credentialId.toString('base64url')); assert.strictEqual(keyDoneResponse.body.name, keyName); - const usersShowResponse = await api('/users/show', { + const usersShowResponse = await api('users/show', { username, }); assert.strictEqual(usersShowResponse.status, 200); assert.strictEqual(usersShowResponse.body.securityKeys, true); - const signinResponse = await api('/signin', { + const signinResponse = await api('signin', { ...signinParam(), }); assert.strictEqual(signinResponse.status, 200); @@ -268,7 +268,7 @@ describe('2要素認証', () => { assert.notEqual(signinResponse.body.allowCredentials, undefined); assert.strictEqual(signinResponse.body.allowCredentials[0].id, credentialId.toString('base64url')); - const signinResponse2 = await api('/signin', signinWithSecurityKeyParam({ + const signinResponse2 = await api('signin', signinWithSecurityKeyParam({ keyName, credentialId, requestOptions: signinResponse.body, @@ -277,24 +277,24 @@ describe('2要素認証', () => { assert.notEqual(signinResponse2.body.i, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); }); test('が設定でき、セキュリティキーでパスワードレスログインできる。', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const registerKeyResponse = await api('/i/2fa/register-key', { + const registerKeyResponse = await api('i/2fa/register-key', { token: otpToken(registerResponse.body.secret), password, }, alice); @@ -302,33 +302,33 @@ describe('2要素認証', () => { const keyName = 'example-key'; const credentialId = crypto.randomBytes(0x41); - const keyDoneResponse = await api('/i/2fa/key-done', keyDoneParam({ + const keyDoneResponse = await api('i/2fa/key-done', keyDoneParam({ token: otpToken(registerResponse.body.secret), keyName, credentialId, creationOptions: registerKeyResponse.body, - }), alice); + }) as any, alice); assert.strictEqual(keyDoneResponse.status, 200); - const passwordLessResponse = await api('/i/2fa/password-less', { + const passwordLessResponse = await api('i/2fa/password-less', { value: true, }, alice); assert.strictEqual(passwordLessResponse.status, 204); - const usersShowResponse = await api('/users/show', { + const usersShowResponse = await api('users/show', { username, }); assert.strictEqual(usersShowResponse.status, 200); assert.strictEqual(usersShowResponse.body.usePasswordLessLogin, true); - const signinResponse = await api('/signin', { + const signinResponse = await api('signin', { ...signinParam(), password: '', }); assert.strictEqual(signinResponse.status, 200); assert.strictEqual(signinResponse.body.i, undefined); - const signinResponse2 = await api('/signin', { + const signinResponse2 = await api('signin', { ...signinWithSecurityKeyParam({ keyName, credentialId, @@ -340,24 +340,24 @@ describe('2要素認証', () => { assert.notEqual(signinResponse2.body.i, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); }); test('が設定でき、設定したセキュリティキーの名前を変更できる。', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const registerKeyResponse = await api('/i/2fa/register-key', { + const registerKeyResponse = await api('i/2fa/register-key', { token: otpToken(registerResponse.body.secret), password, }, alice); @@ -365,22 +365,22 @@ describe('2要素認証', () => { const keyName = 'example-key'; const credentialId = crypto.randomBytes(0x41); - const keyDoneResponse = await api('/i/2fa/key-done', keyDoneParam({ + const keyDoneResponse = await api('i/2fa/key-done', keyDoneParam({ token: otpToken(registerResponse.body.secret), keyName, credentialId, creationOptions: registerKeyResponse.body, - }), alice); + }) as any, alice); assert.strictEqual(keyDoneResponse.status, 200); const renamedKey = 'other-key'; - const updateKeyResponse = await api('/i/2fa/update-key', { + const updateKeyResponse = await api('i/2fa/update-key', { name: renamedKey, credentialId: credentialId.toString('base64url'), }, alice); assert.strictEqual(updateKeyResponse.status, 200); - const iResponse = await api('/i', { + const iResponse = await api('i', { }, alice); assert.strictEqual(iResponse.status, 200); const securityKeys = iResponse.body.securityKeysList.filter((s: { id: string; }) => s.id === credentialId.toString('base64url')); @@ -389,24 +389,24 @@ describe('2要素認証', () => { assert.notEqual(securityKeys[0].lastUsed, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); }); test('が設定でき、設定したセキュリティキーを削除できる。', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const registerKeyResponse = await api('/i/2fa/register-key', { + const registerKeyResponse = await api('i/2fa/register-key', { token: otpToken(registerResponse.body.secret), password, }, alice); @@ -414,20 +414,20 @@ describe('2要素認証', () => { const keyName = 'example-key'; const credentialId = crypto.randomBytes(0x41); - const keyDoneResponse = await api('/i/2fa/key-done', keyDoneParam({ + const keyDoneResponse = await api('i/2fa/key-done', keyDoneParam({ token: otpToken(registerResponse.body.secret), keyName, credentialId, creationOptions: registerKeyResponse.body, - }), alice); + }) as any, alice); assert.strictEqual(keyDoneResponse.status, 200); // テストの実行順によっては複数残ってるので全部消す - const iResponse = await api('/i', { + const iResponse = await api('i', { }, alice); assert.strictEqual(iResponse.status, 200); for (const key of iResponse.body.securityKeysList) { - const removeKeyResponse = await api('/i/2fa/remove-key', { + const removeKeyResponse = await api('i/2fa/remove-key', { token: otpToken(registerResponse.body.secret), password, credentialId: key.id, @@ -435,13 +435,13 @@ describe('2要素認証', () => { assert.strictEqual(removeKeyResponse.status, 200); } - const usersShowResponse = await api('/users/show', { + const usersShowResponse = await api('users/show', { username, }); assert.strictEqual(usersShowResponse.status, 200); assert.strictEqual(usersShowResponse.body.securityKeys, false); - const signinResponse = await api('/signin', { + const signinResponse = await api('signin', { ...signinParam(), token: otpToken(registerResponse.body.secret), }); @@ -449,43 +449,43 @@ describe('2要素認証', () => { assert.notEqual(signinResponse.body.i, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); }); test('が設定でき、設定解除できる。(パスワードのみでログインできる。)', async () => { - const registerResponse = await api('/i/2fa/register', { + const registerResponse = await api('i/2fa/register', { password, }, alice); assert.strictEqual(registerResponse.status, 200); - const doneResponse = await api('/i/2fa/done', { + const doneResponse = await api('i/2fa/done', { token: otpToken(registerResponse.body.secret), }, alice); assert.strictEqual(doneResponse.status, 200); - const usersShowResponse = await api('/users/show', { + const usersShowResponse = await api('users/show', { username, }); assert.strictEqual(usersShowResponse.status, 200); assert.strictEqual(usersShowResponse.body.twoFactorEnabled, true); - const unregisterResponse = await api('/i/2fa/unregister', { + const unregisterResponse = await api('i/2fa/unregister', { token: otpToken(registerResponse.body.secret), password, }, alice); assert.strictEqual(unregisterResponse.status, 204); - const signinResponse = await api('/signin', { + const signinResponse = await api('signin', { ...signinParam(), }); assert.strictEqual(signinResponse.status, 200); assert.notEqual(signinResponse.body.i, undefined); // 後片付け - await api('/i/2fa/unregister', { + await api('i/2fa/unregister', { password, token: otpToken(registerResponse.body.secret), }, alice); diff --git a/packages/backend/test/e2e/antennas.ts b/packages/backend/test/e2e/antennas.ts index 1a9d5bf1f0..101238b601 100644 --- a/packages/backend/test/e2e/antennas.ts +++ b/packages/backend/test/e2e/antennas.ts @@ -7,7 +7,6 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; import { DEFAULT_POLICIES } from '@/core/RoleService.js'; -import type { Packed } from '@/misc/json-schema.js'; import { api, failedApiCall, @@ -29,10 +28,7 @@ describe('アンテナ', () => { // エンティティとしてのアンテナを主眼においたテストを記述する // (Antennaを返すエンドポイント、Antennaエンティティを書き換えるエンドポイント、Antennaからノートを取得するエンドポイントをテストする) - // BUG misskey-jsとjson-schemaが一致していない。 - // - srcのenumにgroupが残っている - // - userGroupIdが残っている, isActiveがない - type Antenna = misskey.entities.Antenna | Packed<'Antenna'>; + type Antenna = misskey.entities.Antenna; type User = misskey.entities.SignupResponse; type Note = misskey.entities.Note; @@ -42,12 +38,12 @@ describe('アンテナ', () => { excludeKeywords: [['']], keywords: [['keyword']], name: 'test', - notify: false, src: 'all' as const, userListId: null, users: [''], withFile: false, withReplies: false, + excludeBots: false, }; let root: User; @@ -80,7 +76,7 @@ describe('アンテナ', () => { aliceList = await userList(alice, {}); bob = await signup({ username: 'bob' }); aliceList = await userList(alice, {}); - bobFile = (await uploadFile(bob)).body; + bobFile = (await uploadFile(bob)).body!; bobList = await userList(bob); carol = await signup({ username: 'carol' }); await api('users/lists/push', { listId: aliceList.id, userId: bob.id }, alice); @@ -129,9 +125,9 @@ describe('アンテナ', () => { beforeEach(async () => { // テスト間で影響し合わないように毎回全部消す。 for (const user of [alice, bob]) { - const list = await api('/antennas/list', {}, user); + const list = await api('antennas/list', {}, user); for (const antenna of list.body) { - await api('/antennas/delete', { antennaId: antenna.id }, user); + await api('antennas/delete', { antennaId: antenna.id }, user); } } }); @@ -141,11 +137,11 @@ describe('アンテナ', () => { test('が作成できること、キーが過不足なく入っていること。', async () => { const response = await successfulApiCall({ endpoint: 'antennas/create', - parameters: { ...defaultParam }, + parameters: defaultParam, user: alice, }); assert.match(response.id, /[0-9a-z]{10}/); - const expected = { + const expected: Antenna = { id: response.id, caseSensitive: false, createdAt: new Date(response.createdAt).toISOString(), @@ -154,14 +150,15 @@ describe('アンテナ', () => { isActive: true, keywords: [['keyword']], name: 'test', - notify: false, src: 'all', userListId: null, users: [''], withFile: false, withReplies: false, + excludeBots: false, localOnly: false, - } as Antenna; + notify: false, + }; assert.deepStrictEqual(response, expected); }); @@ -202,27 +199,25 @@ describe('アンテナ', () => { }); const antennaParamPattern = [ - { parameters: (): object => ({ name: 'x'.repeat(100) }) }, - { parameters: (): object => ({ name: 'x' }) }, - { parameters: (): object => ({ src: 'home' }) }, - { parameters: (): object => ({ src: 'all' }) }, - { parameters: (): object => ({ src: 'users' }) }, - { parameters: (): object => ({ src: 'list' }) }, - { parameters: (): object => ({ userListId: null }) }, - { parameters: (): object => ({ src: 'list', userListId: aliceList.id }) }, - { parameters: (): object => ({ keywords: [['x']] }) }, - { parameters: (): object => ({ keywords: [['a', 'b', 'c'], ['x'], ['y'], ['z']] }) }, - { parameters: (): object => ({ excludeKeywords: [['a', 'b', 'c'], ['x'], ['y'], ['z']] }) }, - { parameters: (): object => ({ users: [alice.username] }) }, - { parameters: (): object => ({ users: [alice.username, bob.username, carol.username] }) }, - { parameters: (): object => ({ caseSensitive: false }) }, - { parameters: (): object => ({ caseSensitive: true }) }, - { parameters: (): object => ({ withReplies: false }) }, - { parameters: (): object => ({ withReplies: true }) }, - { parameters: (): object => ({ withFile: false }) }, - { parameters: (): object => ({ withFile: true }) }, - { parameters: (): object => ({ notify: false }) }, - { parameters: (): object => ({ notify: true }) }, + { parameters: () => ({ name: 'x'.repeat(100) }) }, + { parameters: () => ({ name: 'x' }) }, + { parameters: () => ({ src: 'home' as const }) }, + { parameters: () => ({ src: 'all' as const }) }, + { parameters: () => ({ src: 'users' as const }) }, + { parameters: () => ({ src: 'list' as const }) }, + { parameters: () => ({ userListId: null }) }, + { parameters: () => ({ src: 'list' as const, userListId: aliceList.id }) }, + { parameters: () => ({ keywords: [['x']] }) }, + { parameters: () => ({ keywords: [['a', 'b', 'c'], ['x'], ['y'], ['z']] }) }, + { parameters: () => ({ excludeKeywords: [['a', 'b', 'c'], ['x'], ['y'], ['z']] }) }, + { parameters: () => ({ users: [alice.username] }) }, + { parameters: () => ({ users: [alice.username, bob.username, carol.username] }) }, + { parameters: () => ({ caseSensitive: false }) }, + { parameters: () => ({ caseSensitive: true }) }, + { parameters: () => ({ withReplies: false }) }, + { parameters: () => ({ withReplies: true }) }, + { parameters: () => ({ withFile: false }) }, + { parameters: () => ({ withFile: true }) }, ]; test.each(antennaParamPattern)('を作成できること($#)', async ({ parameters }) => { const response = await successfulApiCall({ @@ -335,7 +330,7 @@ describe('アンテナ', () => { test.each([ { label: '全体から', - parameters: (): object => ({ src: 'all' }), + parameters: () => ({ src: 'all' }), posts: [ { note: (): Promise => post(alice, { text: `${keyword}` }), included: true }, { note: (): Promise => post(userFollowedByAlice, { text: `${keyword}` }), included: true }, @@ -346,7 +341,7 @@ describe('アンテナ', () => { { // BUG e4144a1 以降home指定は壊れている(allと同じ) label: 'ホーム指定はallと同じ', - parameters: (): object => ({ src: 'home' }), + parameters: () => ({ src: 'home' }), posts: [ { note: (): Promise => post(alice, { text: `${keyword}` }), included: true }, { note: (): Promise => post(userFollowedByAlice, { text: `${keyword}` }), included: true }, @@ -357,7 +352,7 @@ describe('アンテナ', () => { { // https://github.com/misskey-dev/misskey/issues/9025 label: 'ただし、フォロワー限定投稿とDM投稿を含まない。フォロワーであっても。', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userFollowedByAlice, { text: `${keyword}`, visibility: 'public' }), included: true }, { note: (): Promise => post(userFollowedByAlice, { text: `${keyword}`, visibility: 'home' }), included: true }, @@ -367,56 +362,56 @@ describe('アンテナ', () => { }, { label: 'ブロックしているユーザーのノートは含む', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userBlockedByAlice, { text: `${keyword}` }), included: true }, ], }, { label: 'ブロックされているユーザーのノートは含まない', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userBlockingAlice, { text: `${keyword}` }) }, ], }, { label: 'ミュートしているユーザーのノートは含まない', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userMutedByAlice, { text: `${keyword}` }) }, ], }, { label: 'ミュートされているユーザーのノートは含む', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userMutingAlice, { text: `${keyword}` }), included: true }, ], }, { label: '「見つけやすくする」がOFFのユーザーのノートも含まれる', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userNotExplorable, { text: `${keyword}` }), included: true }, ], }, { label: '鍵付きユーザーのノートも含まれる', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userLocking, { text: `${keyword}` }), included: true }, ], }, { label: 'サイレンスのノートも含まれる', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userSilenced, { text: `${keyword}` }), included: true }, ], }, { label: '削除ユーザーのノートも含まれる', - parameters: (): object => ({}), + parameters: () => ({}), posts: [ { note: (): Promise => post(userDeletedBySelf, { text: `${keyword}` }), included: true }, { note: (): Promise => post(userDeletedByAdmin, { text: `${keyword}` }), included: true }, @@ -424,7 +419,7 @@ describe('アンテナ', () => { }, { label: 'ユーザー指定で', - parameters: (): object => ({ src: 'users', users: [`@${bob.username}`, `@${carol.username}`] }), + parameters: () => ({ src: 'users', users: [`@${bob.username}`, `@${carol.username}`] }), posts: [ { note: (): Promise => post(alice, { text: `test ${keyword}` }) }, { note: (): Promise => post(bob, { text: `test ${keyword}` }), included: true }, @@ -433,7 +428,7 @@ describe('アンテナ', () => { }, { label: 'リスト指定で', - parameters: (): object => ({ src: 'list', userListId: aliceList.id }), + parameters: () => ({ src: 'list', userListId: aliceList.id }), posts: [ { note: (): Promise => post(alice, { text: `test ${keyword}` }) }, { note: (): Promise => post(bob, { text: `test ${keyword}` }), included: true }, @@ -442,14 +437,14 @@ describe('アンテナ', () => { }, { label: 'CWにもマッチする', - parameters: (): object => ({ keywords: [[keyword]] }), + parameters: () => ({ keywords: [[keyword]] }), posts: [ { note: (): Promise => post(bob, { text: 'test', cw: `cw ${keyword}` }), included: true }, ], }, { label: 'キーワード1つ', - parameters: (): object => ({ keywords: [[keyword]] }), + parameters: () => ({ keywords: [[keyword]] }), posts: [ { note: (): Promise => post(alice, { text: 'test' }) }, { note: (): Promise => post(bob, { text: `test ${keyword}` }), included: true }, @@ -458,7 +453,7 @@ describe('アンテナ', () => { }, { label: 'キーワード3つ(AND)', - parameters: (): object => ({ keywords: [['A', 'B', 'C']] }), + parameters: () => ({ keywords: [['A', 'B', 'C']] }), posts: [ { note: (): Promise => post(bob, { text: 'test A' }) }, { note: (): Promise => post(bob, { text: 'test A B' }) }, @@ -469,7 +464,7 @@ describe('アンテナ', () => { }, { label: 'キーワード3つ(OR)', - parameters: (): object => ({ keywords: [['A'], ['B'], ['C']] }), + parameters: () => ({ keywords: [['A'], ['B'], ['C']] }), posts: [ { note: (): Promise => post(bob, { text: 'test' }) }, { note: (): Promise => post(bob, { text: 'test A' }), included: true }, @@ -482,7 +477,7 @@ describe('アンテナ', () => { }, { label: '除外ワード3つ(AND)', - parameters: (): object => ({ excludeKeywords: [['A', 'B', 'C']] }), + parameters: () => ({ excludeKeywords: [['A', 'B', 'C']] }), posts: [ { note: (): Promise => post(bob, { text: `test ${keyword}` }), included: true }, { note: (): Promise => post(bob, { text: `test ${keyword} A` }), included: true }, @@ -495,7 +490,7 @@ describe('アンテナ', () => { }, { label: '除外ワード3つ(OR)', - parameters: (): object => ({ excludeKeywords: [['A'], ['B'], ['C']] }), + parameters: () => ({ excludeKeywords: [['A'], ['B'], ['C']] }), posts: [ { note: (): Promise => post(bob, { text: `test ${keyword}` }), included: true }, { note: (): Promise => post(bob, { text: `test ${keyword} A` }) }, @@ -508,7 +503,7 @@ describe('アンテナ', () => { }, { label: 'キーワード1つ(大文字小文字区別する)', - parameters: (): object => ({ keywords: [['KEYWORD']], caseSensitive: true }), + parameters: () => ({ keywords: [['KEYWORD']], caseSensitive: true }), posts: [ { note: (): Promise => post(bob, { text: 'keyword' }) }, { note: (): Promise => post(bob, { text: 'kEyWoRd' }) }, @@ -517,7 +512,7 @@ describe('アンテナ', () => { }, { label: 'キーワード1つ(大文字小文字区別しない)', - parameters: (): object => ({ keywords: [['KEYWORD']], caseSensitive: false }), + parameters: () => ({ keywords: [['KEYWORD']], caseSensitive: false }), posts: [ { note: (): Promise => post(bob, { text: 'keyword' }), included: true }, { note: (): Promise => post(bob, { text: 'kEyWoRd' }), included: true }, @@ -526,7 +521,7 @@ describe('アンテナ', () => { }, { label: '除外ワード1つ(大文字小文字区別する)', - parameters: (): object => ({ excludeKeywords: [['KEYWORD']], caseSensitive: true }), + parameters: () => ({ excludeKeywords: [['KEYWORD']], caseSensitive: true }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}` }), included: true }, { note: (): Promise => post(bob, { text: `${keyword} keyword` }), included: true }, @@ -536,7 +531,7 @@ describe('アンテナ', () => { }, { label: '除外ワード1つ(大文字小文字区別しない)', - parameters: (): object => ({ excludeKeywords: [['KEYWORD']], caseSensitive: false }), + parameters: () => ({ excludeKeywords: [['KEYWORD']], caseSensitive: false }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}` }), included: true }, { note: (): Promise => post(bob, { text: `${keyword} keyword` }) }, @@ -546,7 +541,7 @@ describe('アンテナ', () => { }, { label: '添付ファイルを問わない', - parameters: (): object => ({ withFile: false }), + parameters: () => ({ withFile: false }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}`, fileIds: [bobFile.id] }), included: true }, { note: (): Promise => post(bob, { text: `${keyword}` }), included: true }, @@ -554,7 +549,7 @@ describe('アンテナ', () => { }, { label: '添付ファイル付きのみ', - parameters: (): object => ({ withFile: true }), + parameters: () => ({ withFile: true }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}`, fileIds: [bobFile.id] }), included: true }, { note: (): Promise => post(bob, { text: `${keyword}` }) }, @@ -562,7 +557,7 @@ describe('アンテナ', () => { }, { label: 'リプライ以外', - parameters: (): object => ({ withReplies: false }), + parameters: () => ({ withReplies: false }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}`, replyId: alicePost.id }) }, { note: (): Promise => post(bob, { text: `${keyword}` }), included: true }, @@ -570,7 +565,7 @@ describe('アンテナ', () => { }, { label: 'リプライも含む', - parameters: (): object => ({ withReplies: true }), + parameters: () => ({ withReplies: true }), posts: [ { note: (): Promise => post(bob, { text: `${keyword}`, replyId: alicePost.id }), included: true }, { note: (): Promise => post(bob, { text: `${keyword}` }), included: true }, @@ -633,7 +628,7 @@ describe('アンテナ', () => { endpoint: 'antennas/notes', parameters: { antennaId: antenna.id, ...paginationParam }, user: alice, - }) as any as Note[]; + }); }, offsetBy, 'desc'); }); diff --git a/packages/backend/test/e2e/api-visibility.ts b/packages/backend/test/e2e/api-visibility.ts index f92384525c..c61b0c2a86 100644 --- a/packages/backend/test/e2e/api-visibility.ts +++ b/packages/backend/test/e2e/api-visibility.ts @@ -6,7 +6,7 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; -import { api, post, signup } from '../utils.js'; +import { UserToken, api, post, signup } from '../utils.js'; import type * as misskey from 'misskey-js'; describe('API visibility', () => { @@ -24,38 +24,38 @@ describe('API visibility', () => { let target2: misskey.entities.SignupResponse; /** public-post */ - let pub: any; + let pub: misskey.entities.Note; /** home-post */ - let home: any; + let home: misskey.entities.Note; /** followers-post */ - let fol: any; + let fol: misskey.entities.Note; /** specified-post */ - let spe: any; + let spe: misskey.entities.Note; /** public-reply to target's post */ - let pubR: any; + let pubR: misskey.entities.Note; /** home-reply to target's post */ - let homeR: any; + let homeR: misskey.entities.Note; /** followers-reply to target's post */ - let folR: any; + let folR: misskey.entities.Note; /** specified-reply to target's post */ - let speR: any; + let speR: misskey.entities.Note; /** public-mention to target */ - let pubM: any; + let pubM: misskey.entities.Note; /** home-mention to target */ - let homeM: any; + let homeM: misskey.entities.Note; /** followers-mention to target */ - let folM: any; + let folM: misskey.entities.Note; /** specified-mention to target */ - let speM: any; + let speM: misskey.entities.Note; /** reply target post */ - let tgt: any; + let tgt: misskey.entities.Note; //#endregion - const show = async (noteId: any, by: any) => { - return await api('/notes/show', { + const show = async (noteId: misskey.entities.Note['id'], by?: UserToken) => { + return await api('notes/show', { noteId, }, by); }; @@ -70,7 +70,7 @@ describe('API visibility', () => { target2 = await signup({ username: 'target2' }); // follow alice <= follower - await api('/following/create', { userId: alice.id }, follower); + await api('following/create', { userId: alice.id }, follower); // normal posts pub = await post(alice, { text: 'x', visibility: 'public' }); @@ -111,7 +111,7 @@ describe('API visibility', () => { }); test('[show] public-postを未認証が見れる', async () => { - const res = await show(pub.id, null); + const res = await show(pub.id); assert.strictEqual(res.body.text, 'x'); }); @@ -132,7 +132,7 @@ describe('API visibility', () => { }); test('[show] home-postを未認証が見れる', async () => { - const res = await show(home.id, null); + const res = await show(home.id); assert.strictEqual(res.body.text, 'x'); }); @@ -153,7 +153,7 @@ describe('API visibility', () => { }); test('[show] followers-postを未認証が見れない', async () => { - const res = await show(fol.id, null); + const res = await show(fol.id); assert.strictEqual(res.body.isHidden, true); }); @@ -179,7 +179,7 @@ describe('API visibility', () => { }); test('[show] specified-postを未認証が見れない', async () => { - const res = await show(spe.id, null); + const res = await show(spe.id); assert.strictEqual(res.body.isHidden, true); }); //#endregion @@ -207,7 +207,7 @@ describe('API visibility', () => { }); test('[show] public-replyを未認証が見れる', async () => { - const res = await show(pubR.id, null); + const res = await show(pubR.id); assert.strictEqual(res.body.text, 'x'); }); @@ -233,7 +233,7 @@ describe('API visibility', () => { }); test('[show] home-replyを未認証が見れる', async () => { - const res = await show(homeR.id, null); + const res = await show(homeR.id); assert.strictEqual(res.body.text, 'x'); }); @@ -259,7 +259,7 @@ describe('API visibility', () => { }); test('[show] followers-replyを未認証が見れない', async () => { - const res = await show(folR.id, null); + const res = await show(folR.id); assert.strictEqual(res.body.isHidden, true); }); @@ -290,7 +290,7 @@ describe('API visibility', () => { }); test('[show] specified-replyを未認証が見れない', async () => { - const res = await show(speR.id, null); + const res = await show(speR.id); assert.strictEqual(res.body.isHidden, true); }); //#endregion @@ -318,7 +318,7 @@ describe('API visibility', () => { }); test('[show] public-mentionを未認証が見れる', async () => { - const res = await show(pubM.id, null); + const res = await show(pubM.id); assert.strictEqual(res.body.text, '@target x'); }); @@ -344,7 +344,7 @@ describe('API visibility', () => { }); test('[show] home-mentionを未認証が見れる', async () => { - const res = await show(homeM.id, null); + const res = await show(homeM.id); assert.strictEqual(res.body.text, '@target x'); }); @@ -370,7 +370,7 @@ describe('API visibility', () => { }); test('[show] followers-mentionを未認証が見れない', async () => { - const res = await show(folM.id, null); + const res = await show(folM.id); assert.strictEqual(res.body.isHidden, true); }); @@ -401,28 +401,28 @@ describe('API visibility', () => { }); test('[show] specified-mentionを未認証が見れない', async () => { - const res = await show(speM.id, null); + const res = await show(speM.id); assert.strictEqual(res.body.isHidden, true); }); //#endregion //#region HTL test('[HTL] public-post が 自分が見れる', async () => { - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === pub.id); assert.strictEqual(notes[0].text, 'x'); }); test('[HTL] public-post が 非フォロワーから見れない', async () => { - const res = await api('/notes/timeline', { limit: 100 }, other); + const res = await api('notes/timeline', { limit: 100 }, other); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === pub.id); assert.strictEqual(notes.length, 0); }); test('[HTL] followers-post が フォロワーから見れる', async () => { - const res = await api('/notes/timeline', { limit: 100 }, follower); + const res = await api('notes/timeline', { limit: 100 }, follower); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === fol.id); assert.strictEqual(notes[0].text, 'x'); @@ -431,21 +431,21 @@ describe('API visibility', () => { //#region RTL test('[replies] followers-reply が フォロワーから見れる', async () => { - const res = await api('/notes/replies', { noteId: tgt.id, limit: 100 }, follower); + const res = await api('notes/replies', { noteId: tgt.id, limit: 100 }, follower); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === folR.id); assert.strictEqual(notes[0].text, 'x'); }); test('[replies] followers-reply が 非フォロワー (リプライ先ではない) から見れない', async () => { - const res = await api('/notes/replies', { noteId: tgt.id, limit: 100 }, other); + const res = await api('notes/replies', { noteId: tgt.id, limit: 100 }, other); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === folR.id); assert.strictEqual(notes.length, 0); }); test('[replies] followers-reply が 非フォロワー (リプライ先である) から見れる', async () => { - const res = await api('/notes/replies', { noteId: tgt.id, limit: 100 }, target); + const res = await api('notes/replies', { noteId: tgt.id, limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === folR.id); assert.strictEqual(notes[0].text, 'x'); @@ -454,14 +454,14 @@ describe('API visibility', () => { //#region MTL test('[mentions] followers-reply が 非フォロワー (リプライ先である) から見れる', async () => { - const res = await api('/notes/mentions', { limit: 100 }, target); + const res = await api('notes/mentions', { limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === folR.id); assert.strictEqual(notes[0].text, 'x'); }); test('[mentions] followers-mention が 非フォロワー (メンション先である) から見れる', async () => { - const res = await api('/notes/mentions', { limit: 100 }, target); + const res = await api('notes/mentions', { limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id === folM.id); assert.strictEqual(notes[0].text, '@target x'); diff --git a/packages/backend/test/e2e/api.ts b/packages/backend/test/e2e/api.ts index b6eeec99d7..49c6a0636b 100644 --- a/packages/backend/test/e2e/api.ts +++ b/packages/backend/test/e2e/api.ts @@ -23,32 +23,32 @@ import type * as misskey from 'misskey-js'; describe('API', () => { let alice: misskey.entities.SignupResponse; let bob: misskey.entities.SignupResponse; - let carol: misskey.entities.SignupResponse; beforeAll(async () => { alice = await signup({ username: 'alice' }); bob = await signup({ username: 'bob' }); - carol = await signup({ username: 'carol' }); }, 1000 * 60 * 2); describe('General validation', () => { test('wrong type', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, + // @ts-expect-error string must be string string: 42, }); assert.strictEqual(res.status, 400); }); test('missing require param', async () => { - const res = await api('/test', { + // @ts-expect-error required is required + const res = await api('test', { string: 'a', }); assert.strictEqual(res.status, 400); }); test('invalid misskey:id (empty string)', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, id: '', }); @@ -56,7 +56,7 @@ describe('API', () => { }); test('valid misskey:id', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, id: '8wvhjghbxu', }); @@ -64,7 +64,7 @@ describe('API', () => { }); test('default value', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, string: 'a', }); @@ -73,7 +73,7 @@ describe('API', () => { }); test('can set null even if it has default value', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, nullableDefault: null, }); @@ -82,7 +82,7 @@ describe('API', () => { }); test('cannot set undefined if it has default value', async () => { - const res = await api('/test', { + const res = await api('test', { required: true, nullableDefault: undefined, }); @@ -99,14 +99,14 @@ describe('API', () => { // aliceは管理者、APIを使える await successfulApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: alice, }); // bobは一般ユーザーだからダメ await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: bob, }, { @@ -117,7 +117,7 @@ describe('API', () => { // publicアクセスももちろんダメ await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: undefined, }, { @@ -128,7 +128,7 @@ describe('API', () => { // ごまがしもダメ await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: 'tsukawasete' }, }, { @@ -138,13 +138,13 @@ describe('API', () => { }); await successfulApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: application2 }, }); await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: application }, }, { @@ -154,7 +154,7 @@ describe('API', () => { }); await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: application3 }, }, { @@ -164,7 +164,7 @@ describe('API', () => { }); await failedApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: application4 }, }, { @@ -177,7 +177,7 @@ describe('API', () => { describe('Authentication header', () => { test('一般リクエスト', async () => { await successfulApiCall({ - endpoint: '/admin/get-index-stats', + endpoint: 'admin/get-index-stats', parameters: {}, user: { token: alice.token, @@ -211,7 +211,7 @@ describe('API', () => { describe('tokenエラー応答でWWW-Authenticate headerを送る', () => { describe('invalid_token', () => { test('一般リクエスト', async () => { - const result = await api('/admin/get-index-stats', {}, { + const result = await api('admin/get-index-stats', {}, { token: 'syuilo', bearer: true, }); @@ -246,7 +246,7 @@ describe('API', () => { describe('tokenがないとrealmだけおくる', () => { test('一般リクエスト', async () => { - const result = await api('/admin/get-index-stats', {}); + const result = await api('admin/get-index-stats', {}); assert.strictEqual(result.status, 401); assert.strictEqual(result.headers.get('WWW-Authenticate'), 'Bearer realm="Misskey"'); }); @@ -259,7 +259,8 @@ describe('API', () => { }); test('invalid_request', async () => { - const result = await api('/notes/create', { text: true }, { + // @ts-expect-error text must be string + const result = await api('notes/create', { text: true }, { token: alice.token, bearer: true, }); diff --git a/packages/backend/test/e2e/block.ts b/packages/backend/test/e2e/block.ts index cbd91e6e42..e4f798498f 100644 --- a/packages/backend/test/e2e/block.ts +++ b/packages/backend/test/e2e/block.ts @@ -22,7 +22,7 @@ describe('Block', () => { }, 1000 * 60 * 2); test('Block作成', async () => { - const res = await api('/blocking/create', { + const res = await api('blocking/create', { userId: bob.id, }, alice); @@ -30,7 +30,7 @@ describe('Block', () => { }); test('ブロックされているユーザーをフォローできない', async () => { - const res = await api('/following/create', { userId: alice.id }, bob); + const res = await api('following/create', { userId: alice.id }, bob); assert.strictEqual(res.status, 400); assert.strictEqual(res.body.error.id, 'c4ab57cc-4e41-45e9-bfd9-584f61e35ce0'); @@ -39,7 +39,7 @@ describe('Block', () => { test('ブロックされているユーザーにリアクションできない', async () => { const note = await post(alice, { text: 'hello' }); - const res = await api('/notes/reactions/create', { noteId: note.id, reaction: '👍' }, bob); + const res = await api('notes/reactions/create', { noteId: note.id, reaction: '👍' }, bob); assert.strictEqual(res.status, 400); assert.strictEqual(res.body.error.id, '20ef5475-9f38-4e4c-bd33-de6d979498ec'); @@ -48,7 +48,7 @@ describe('Block', () => { test('ブロックされているユーザーに返信できない', async () => { const note = await post(alice, { text: 'hello' }); - const res = await api('/notes/create', { replyId: note.id, text: 'yo' }, bob); + const res = await api('notes/create', { replyId: note.id, text: 'yo' }, bob); assert.strictEqual(res.status, 400); assert.strictEqual(res.body.error.id, 'b390d7e1-8a5e-46ed-b625-06271cafd3d3'); @@ -57,7 +57,7 @@ describe('Block', () => { test('ブロックされているユーザーのノートをRenoteできない', async () => { const note = await post(alice, { text: 'hello' }); - const res = await api('/notes/create', { renoteId: note.id, text: 'yo' }, bob); + const res = await api('notes/create', { renoteId: note.id, text: 'yo' }, bob); assert.strictEqual(res.status, 400); assert.strictEqual(res.body.error.id, 'b390d7e1-8a5e-46ed-b625-06271cafd3d3'); @@ -72,12 +72,13 @@ describe('Block', () => { const bobNote = await post(bob, { text: 'hi' }); const carolNote = await post(carol, { text: 'hi' }); - const res = await api('/notes/local-timeline', {}, bob); + const res = await api('notes/local-timeline', {}, bob); + const body = res.body as misskey.entities.Note[]; assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), false); - assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); - assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); + assert.strictEqual(body.some(note => note.id === aliceNote.id), false); + assert.strictEqual(body.some(note => note.id === bobNote.id), true); + assert.strictEqual(body.some(note => note.id === carolNote.id), true); }); }); diff --git a/packages/backend/test/e2e/clips.ts b/packages/backend/test/e2e/clips.ts index 2cf397e22d..ba6f9d6a65 100644 --- a/packages/backend/test/e2e/clips.ts +++ b/packages/backend/test/e2e/clips.ts @@ -6,47 +6,34 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; -import { JTDDataType } from 'ajv/dist/jtd'; import { DEFAULT_POLICIES } from '@/core/RoleService.js'; -import type { Packed } from '@/misc/json-schema.js'; -import { paramDef as CreateParamDef } from '@/server/api/endpoints/clips/create.js'; -import { paramDef as UpdateParamDef } from '@/server/api/endpoints/clips/update.js'; -import { paramDef as DeleteParamDef } from '@/server/api/endpoints/clips/delete.js'; -import { paramDef as ShowParamDef } from '@/server/api/endpoints/clips/show.js'; -import { paramDef as FavoriteParamDef } from '@/server/api/endpoints/clips/favorite.js'; -import { paramDef as UnfavoriteParamDef } from '@/server/api/endpoints/clips/unfavorite.js'; -import { paramDef as AddNoteParamDef } from '@/server/api/endpoints/clips/add-note.js'; -import { paramDef as RemoveNoteParamDef } from '@/server/api/endpoints/clips/remove-note.js'; -import { paramDef as NotesParamDef } from '@/server/api/endpoints/clips/notes.js'; import { api, ApiRequest, failedApiCall, hiddenNote, post, signup, successfulApiCall } from '../utils.js'; +import type * as Misskey from 'misskey-js'; + +type Optional = Pick, K> & Omit; describe('クリップ', () => { - type User = Packed<'User'>; - type Note = Packed<'Note'>; - type Clip = Packed<'Clip'>; - - let alice: User; - let bob: User; - let aliceNote: Note; - let aliceHomeNote: Note; - let aliceFollowersNote: Note; - let aliceSpecifiedNote: Note; - let bobNote: Note; - let bobHomeNote: Note; - let bobFollowersNote: Note; - let bobSpecifiedNote: Note; + let alice: Misskey.entities.SignupResponse; + let bob: Misskey.entities.SignupResponse; + let aliceNote: Misskey.entities.Note; + let aliceHomeNote: Misskey.entities.Note; + let aliceFollowersNote: Misskey.entities.Note; + let aliceSpecifiedNote: Misskey.entities.Note; + let bobNote: Misskey.entities.Note; + let bobHomeNote: Misskey.entities.Note; + let bobFollowersNote: Misskey.entities.Note; + let bobSpecifiedNote: Misskey.entities.Note; const compareBy = (selector: (s: T) => string = (s: T): string => s.id) => (a: T, b: T): number => { return selector(a).localeCompare(selector(b)); }; - type CreateParam = JTDDataType; - const defaultCreate = (): Partial => ({ + const defaultCreate = (): Pick => ({ name: 'test', }); - const create = async (parameters: Partial = {}, request: Partial = {}): Promise => { - const clip = await successfulApiCall({ - endpoint: '/clips/create', + const create = async (parameters: Partial = {}, request: Partial> = {}): Promise => { + const clip = await successfulApiCall({ + endpoint: 'clips/create', parameters: { ...defaultCreate(), ...parameters, @@ -64,17 +51,16 @@ describe('クリップ', () => { return clip; }; - const createMany = async (parameters: Partial, count = 10, user = alice): Promise => { + const createMany = async (parameters: Partial, count = 10, user = alice): Promise => { return await Promise.all([...Array(count)].map((_, i) => create({ name: `test${i}`, ...parameters, }, { user }))); }; - type UpdateParam = JTDDataType; - const update = async (parameters: Partial, request: Partial = {}): Promise => { - const clip = await successfulApiCall({ - endpoint: '/clips/update', + const update = async (parameters: Optional, request: Partial> = {}): Promise => { + const clip = await successfulApiCall({ + endpoint: 'clips/update', parameters: { name: 'updated', ...parameters, @@ -92,41 +78,39 @@ describe('クリップ', () => { return clip; }; - type DeleteParam = JTDDataType; - const deleteClip = async (parameters: DeleteParam, request: Partial = {}): Promise => { - return await successfulApiCall({ - endpoint: '/clips/delete', + const deleteClip = async (parameters: Misskey.entities.ClipsDeleteRequest, request: Partial> = {}): Promise => { + return await successfulApiCall({ + endpoint: 'clips/delete', parameters, user: alice, ...request, }, { status: 204, - }); + }) as any as void; }; - type ShowParam = JTDDataType; - const show = async (parameters: ShowParam, request: Partial = {}): Promise => { - return await successfulApiCall({ - endpoint: '/clips/show', + const show = async (parameters: Misskey.entities.ClipsShowRequest, request: Partial> = {}): Promise => { + return await successfulApiCall({ + endpoint: 'clips/show', parameters, user: alice, ...request, }); }; - const list = async (request: Partial): Promise => { - return successfulApiCall({ - endpoint: '/clips/list', + const list = async (request: Partial>): Promise => { + return successfulApiCall({ + endpoint: 'clips/list', parameters: {}, user: alice, ...request, }); }; - const usersClips = async (request: Partial): Promise => { - return await successfulApiCall({ - endpoint: '/users/clips', - parameters: {}, + const usersClips = async (parameters: Misskey.entities.UsersClipsRequest, request: Partial> = {}): Promise => { + return await successfulApiCall({ + endpoint: 'users/clips', + parameters, user: alice, ...request, }); @@ -136,23 +120,22 @@ describe('クリップ', () => { alice = await signup({ username: 'alice' }); bob = await signup({ username: 'bob' }); - // FIXME: misskey-jsのNoteはoutdatedなので直接変換できない - aliceNote = await post(alice, { text: 'test' }) as any; - aliceHomeNote = await post(alice, { text: 'home only', visibility: 'home' }) as any; - aliceFollowersNote = await post(alice, { text: 'followers only', visibility: 'followers' }) as any; - aliceSpecifiedNote = await post(alice, { text: 'specified only', visibility: 'specified' }) as any; - bobNote = await post(bob, { text: 'test' }) as any; - bobHomeNote = await post(bob, { text: 'home only', visibility: 'home' }) as any; - bobFollowersNote = await post(bob, { text: 'followers only', visibility: 'followers' }) as any; - bobSpecifiedNote = await post(bob, { text: 'specified only', visibility: 'specified' }) as any; + aliceNote = await post(alice, { text: 'test' }); + aliceHomeNote = await post(alice, { text: 'home only', visibility: 'home' }); + aliceFollowersNote = await post(alice, { text: 'followers only', visibility: 'followers' }); + aliceSpecifiedNote = await post(alice, { text: 'specified only', visibility: 'specified' }); + bobNote = await post(bob, { text: 'test' }); + bobHomeNote = await post(bob, { text: 'home only', visibility: 'home' }); + bobFollowersNote = await post(bob, { text: 'followers only', visibility: 'followers' }); + bobSpecifiedNote = await post(bob, { text: 'specified only', visibility: 'specified' }); }, 1000 * 60 * 2); afterEach(async () => { // テスト間で影響し合わないように毎回全部消す。 for (const user of [alice, bob]) { - const list = await api('/clips/list', { limit: 11 }, user); + const list = await api('clips/list', { limit: 11 }, user); for (const clip of list.body) { - await api('/clips/delete', { clipId: clip.id }, user); + await api('clips/delete', { clipId: clip.id }, user); } } }); @@ -177,7 +160,7 @@ describe('クリップ', () => { } await failedApiCall({ - endpoint: '/clips/create', + endpoint: 'clips/create', parameters: defaultCreate(), user: alice, }, { @@ -204,7 +187,8 @@ describe('クリップ', () => { { label: 'descriptionが最大長+1', parameters: { description: 'a'.repeat(2049) } }, ]; test.each(createClipDenyPattern)('の作成は$labelならできない', async ({ parameters }) => failedApiCall({ - endpoint: '/clips/create', + endpoint: 'clips/create', + // @ts-expect-error invalid params parameters: { ...defaultCreate(), ...parameters, @@ -246,15 +230,15 @@ describe('クリップ', () => { code: 'NO_SUCH_CLIP', id: 'b4d92d70-b216-46fa-9a3f-a8c811699257', } }, - { label: '他人のクリップ', user: (): User => bob, assertion: { + { label: '他人のクリップ', user: () => bob, assertion: { code: 'NO_SUCH_CLIP', id: 'b4d92d70-b216-46fa-9a3f-a8c811699257', } }, ...createClipDenyPattern as any, ])('の更新は$labelならできない', async ({ parameters, user, assertion }) => failedApiCall({ - endpoint: '/clips/update', + endpoint: 'clips/update', parameters: { - clipId: (await create({}, { user: (user ?? ((): User => alice))() })).id, + clipId: (await create({}, { user: (user ?? (() => alice))() })).id, name: 'updated', ...parameters, }, @@ -279,14 +263,15 @@ describe('クリップ', () => { code: 'NO_SUCH_CLIP', id: '70ca08ba-6865-4630-b6fb-8494759aa754', } }, - { label: '他人のクリップ', user: (): User => bob, assertion: { + { label: '他人のクリップ', user: () => bob, assertion: { code: 'NO_SUCH_CLIP', id: '70ca08ba-6865-4630-b6fb-8494759aa754', } }, ])('の削除は$labelならできない', async ({ parameters, user, assertion }) => failedApiCall({ - endpoint: '/clips/delete', + endpoint: 'clips/delete', parameters: { - clipId: (await create({}, { user: (user ?? ((): User => alice))() })).id, + // @ts-expect-error clipId must not be null + clipId: (await create({}, { user: (user ?? (() => alice))() })).id, ...parameters, }, user: alice, @@ -306,7 +291,7 @@ describe('クリップ', () => { test('のID指定取得は他人のPrivateなクリップは取得できない', async () => { const clip = await create({ isPublic: false }, { user: bob } ); failedApiCall({ - endpoint: '/clips/show', + endpoint: 'clips/show', parameters: { clipId: clip.id }, user: alice, }, { @@ -323,7 +308,8 @@ describe('クリップ', () => { id: 'c3c5fe33-d62c-44d2-9ea5-d997703f5c20', } }, ])('のID指定取得は$labelならできない', async ({ parameters, assetion }) => failedApiCall({ - endpoint: '/clips/show', + endpoint: 'clips/show', + // @ts-expect-error clipId must not be undefined parameters: { ...parameters, }, @@ -356,27 +342,23 @@ describe('クリップ', () => { test('の一覧が取得できる(空)', async () => { const res = await usersClips({ - parameters: { - userId: alice.id, - }, + userId: alice.id, }); assert.deepStrictEqual(res, []); }); test.each([ { label: '' }, - { label: '他人アカウントから', user: (): User => bob }, + { label: '他人アカウントから', user: () => bob }, ])('の一覧が$label取得できる', async () => { const clips = await createMany({ isPublic: true }); const res = await usersClips({ - parameters: { - userId: alice.id, - }, + userId: alice.id, }); // 返ってくる配列には順序保障がないのでidでソートして厳密比較 assert.deepStrictEqual( - res.sort(compareBy(s => s.id)), + res.sort(compareBy(s => s.id)), clips.sort(compareBy(s => s.id))); // 認証状態で見たときだけisFavoritedが入っている @@ -386,17 +368,16 @@ describe('クリップ', () => { }); test.each([ - { label: '未認証', user: (): undefined => undefined }, + { label: '未認証', user: () => undefined }, { label: '存在しないユーザーのもの', parameters: { userId: 'xxxxxxx' } }, ])('の一覧は$labelでも取得できる', async ({ parameters, user }) => { const clips = await createMany({ isPublic: true }); const res = await usersClips({ - parameters: { - userId: alice.id, - limit: clips.length, - ...parameters, - }, - user: (user ?? ((): User => alice))(), + userId: alice.id, + limit: clips.length, + ...parameters, + }, { + user: (user ?? (() => alice))(), }); // 未認証で見たときはisFavoritedは入らない @@ -409,10 +390,8 @@ describe('クリップ', () => { await create({ isPublic: false }); const aliceClip = await create({ isPublic: true }); const res = await usersClips({ - parameters: { - userId: alice.id, - limit: 2, - }, + userId: alice.id, + limit: 2, }); assert.deepStrictEqual(res, [aliceClip]); }); @@ -421,17 +400,15 @@ describe('クリップ', () => { const clips = await createMany({ isPublic: true }, 7); clips.sort(compareBy(s => s.id)); const res = await usersClips({ - parameters: { - userId: alice.id, - sinceId: clips[1].id, - untilId: clips[5].id, - limit: 4, - }, + userId: alice.id, + sinceId: clips[1].id, + untilId: clips[5].id, + limit: 4, }); // Promise.allで返ってくる配列には順序保障がないのでidでソートして厳密比較 assert.deepStrictEqual( - res.sort(compareBy(s => s.id)), + res.sort(compareBy(s => s.id)), [clips[2], clips[3], clips[4]], // sinceIdとuntilId自体は結果に含まれない clips[1].id + ' ... ' + clips[3].id + ' with ' + clips.map(s => s.id) + ' vs. ' + res.map(s => s.id)); }); @@ -441,8 +418,9 @@ describe('クリップ', () => { { label: 'limitゼロ', parameters: { limit: 0 } }, { label: 'limit最大+1', parameters: { limit: 101 } }, ])('の一覧は$labelだと取得できない', async ({ parameters }) => failedApiCall({ - endpoint: '/users/clips', + endpoint: 'users/clips', parameters: { + // @ts-expect-error userId must not be undefined userId: alice.id, ...parameters, }, @@ -454,15 +432,15 @@ describe('クリップ', () => { })); test.each([ - { label: '作成', endpoint: '/clips/create' }, - { label: '更新', endpoint: '/clips/update' }, - { label: '削除', endpoint: '/clips/delete' }, - { label: '取得', endpoint: '/clips/list' }, - { label: 'お気に入り設定', endpoint: '/clips/favorite' }, - { label: 'お気に入り解除', endpoint: '/clips/unfavorite' }, - { label: 'お気に入り取得', endpoint: '/clips/my-favorites' }, - { label: 'ノート追加', endpoint: '/clips/add-note' }, - { label: 'ノート削除', endpoint: '/clips/remove-note' }, + { label: '作成', endpoint: 'clips/create' as const }, + { label: '更新', endpoint: 'clips/update' as const }, + { label: '削除', endpoint: 'clips/delete' as const }, + { label: '取得', endpoint: 'clips/list' as const }, + { label: 'お気に入り設定', endpoint: 'clips/favorite' as const }, + { label: 'お気に入り解除', endpoint: 'clips/unfavorite' as const }, + { label: 'お気に入り取得', endpoint: 'clips/my-favorites' as const }, + { label: 'ノート追加', endpoint: 'clips/add-note' as const }, + { label: 'ノート削除', endpoint: 'clips/remove-note' as const }, ])('の$labelは未認証ではできない', async ({ endpoint }) => await failedApiCall({ endpoint: endpoint, parameters: {}, @@ -474,35 +452,33 @@ describe('クリップ', () => { })); describe('のお気に入り', () => { - let aliceClip: Clip; + let aliceClip: Misskey.entities.Clip; - type FavoriteParam = JTDDataType; - const favorite = async (parameters: FavoriteParam, request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/favorite', + const favorite = async (parameters: Misskey.entities.ClipsFavoriteRequest, request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/favorite', parameters, user: alice, ...request, }, { status: 204, - }); + }) as any as void; }; - type UnfavoriteParam = JTDDataType; - const unfavorite = async (parameters: UnfavoriteParam, request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/unfavorite', + const unfavorite = async (parameters: Misskey.entities.ClipsUnfavoriteRequest, request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/unfavorite', parameters, user: alice, ...request, }, { status: 204, - }); + }) as any as void; }; - const myFavorites = async (request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/my-favorites', + const myFavorites = async (request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/my-favorites', parameters: {}, user: alice, ...request, @@ -568,7 +544,7 @@ describe('クリップ', () => { test('は同じクリップに対して二回設定できない。', async () => { await favorite({ clipId: aliceClip.id }); await failedApiCall({ - endpoint: '/clips/favorite', + endpoint: 'clips/favorite', parameters: { clipId: aliceClip.id, }, @@ -586,14 +562,15 @@ describe('クリップ', () => { code: 'NO_SUCH_CLIP', id: '4c2aaeae-80d8-4250-9606-26cb1fdb77a5', } }, - { label: '他人のクリップ', user: (): User => bob, assertion: { + { label: '他人のクリップ', user: () => bob, assertion: { code: 'NO_SUCH_CLIP', id: '4c2aaeae-80d8-4250-9606-26cb1fdb77a5', } }, ])('の設定は$labelならできない', async ({ parameters, user, assertion }) => failedApiCall({ - endpoint: '/clips/favorite', + endpoint: 'clips/favorite', parameters: { - clipId: (await create({}, { user: (user ?? ((): User => alice))() })).id, + // @ts-expect-error clipId must not be null + clipId: (await create({}, { user: (user ?? (() => alice))() })).id, ...parameters, }, user: alice, @@ -619,7 +596,7 @@ describe('クリップ', () => { code: 'NO_SUCH_CLIP', id: '2603966e-b865-426c-94a7-af4a01241dc1', } }, - { label: '他人のクリップ', user: (): User => bob, assertion: { + { label: '他人のクリップ', user: () => bob, assertion: { code: 'NOT_FAVORITED', id: '90c3a9e8-b321-4dae-bf57-2bf79bbcc187', } }, @@ -628,9 +605,10 @@ describe('クリップ', () => { id: '90c3a9e8-b321-4dae-bf57-2bf79bbcc187', } }, ])('の設定解除は$labelならできない', async ({ parameters, user, assertion }) => failedApiCall({ - endpoint: '/clips/unfavorite', + endpoint: 'clips/unfavorite', parameters: { - clipId: (await create({}, { user: (user ?? ((): User => alice))() })).id, + // @ts-expect-error clipId must not be null + clipId: (await create({}, { user: (user ?? (() => alice))() })).id, ...parameters, }, user: alice, @@ -655,41 +633,38 @@ describe('クリップ', () => { }); describe('に紐づくノート', () => { - let aliceClip: Clip; + let aliceClip: Misskey.entities.Clip; - const sampleNotes = (): Note[] => [ + const sampleNotes = (): Misskey.entities.Note[] => [ aliceNote, aliceHomeNote, aliceFollowersNote, aliceSpecifiedNote, bobNote, bobHomeNote, bobFollowersNote, bobSpecifiedNote, ]; - type AddNoteParam = JTDDataType; - const addNote = async (parameters: AddNoteParam, request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/add-note', + const addNote = async (parameters: Misskey.entities.ClipsAddNoteRequest, request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/add-note', parameters, user: alice, ...request, }, { status: 204, - }); + }) as any as void; }; - type RemoveNoteParam = JTDDataType; - const removeNote = async (parameters: RemoveNoteParam, request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/remove-note', + const removeNote = async (parameters: Misskey.entities.ClipsRemoveNoteRequest, request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/remove-note', parameters, user: alice, ...request, }, { status: 204, - }); + }) as any as void; }; - type NotesParam = JTDDataType; - const notes = async (parameters: Partial, request: Partial = {}): Promise => { - return successfulApiCall({ - endpoint: '/clips/notes', + const notes = async (parameters: Misskey.entities.ClipsNotesRequest, request: Partial> = {}): Promise => { + return successfulApiCall({ + endpoint: 'clips/notes', parameters, user: alice, ...request, @@ -715,7 +690,7 @@ describe('クリップ', () => { test('として同じノートを二回紐づけることはできない', async () => { await addNote({ clipId: aliceClip.id, noteId: aliceNote.id }); await failedApiCall({ - endpoint: '/clips/add-note', + endpoint: 'clips/add-note', parameters: { clipId: aliceClip.id, noteId: aliceNote.id, @@ -733,11 +708,11 @@ describe('クリップ', () => { const noteLimit = DEFAULT_POLICIES.noteEachClipsLimit + 1; const noteList = await Promise.all([...Array(noteLimit)].map((_, i) => post(alice, { text: `test ${i}`, - }) as unknown)) as Note[]; + }) as unknown)) as Misskey.entities.Note[]; await Promise.all(noteList.map(s => addNote({ clipId: aliceClip.id, noteId: s.id }))); await failedApiCall({ - endpoint: '/clips/add-note', + endpoint: 'clips/add-note', parameters: { clipId: aliceClip.id, noteId: aliceNote.id, @@ -751,7 +726,7 @@ describe('クリップ', () => { }); test('は他人のクリップへ追加できない。', async () => await failedApiCall({ - endpoint: '/clips/add-note', + endpoint: 'clips/add-note', parameters: { clipId: aliceClip.id, noteId: aliceNote.id, @@ -774,18 +749,20 @@ describe('クリップ', () => { code: 'NO_SUCH_NOTE', id: 'fc8c0b49-c7a3-4664-a0a6-b418d386bb8b', } }, - { label: '他人のクリップ', user: (): object => bob, assetion: { + { label: '他人のクリップ', user: () => bob, assetion: { code: 'NO_SUCH_CLIP', id: 'd6e76cc0-a1b5-4c7c-a287-73fa9c716dcf', } }, ])('の追加は$labelだとできない', async ({ parameters, user, assetion }) => failedApiCall({ - endpoint: '/clips/add-note', + endpoint: 'clips/add-note', parameters: { + // @ts-expect-error clipId must not be undefined clipId: aliceClip.id, + // @ts-expect-error noteId must not be undefined noteId: aliceNote.id, ...parameters, }, - user: (user ?? ((): User => alice))(), + user: (user ?? (() => alice))(), }, { status: 400, code: 'INVALID_PARAM', @@ -810,18 +787,20 @@ describe('クリップ', () => { code: 'NO_SUCH_NOTE', id: 'aff017de-190e-434b-893e-33a9ff5049d8', // add-noteと異なる } }, - { label: '他人のクリップ', user: (): object => bob, assetion: { + { label: '他人のクリップ', user: () => bob, assetion: { code: 'NO_SUCH_CLIP', id: 'b80525c6-97f7-49d7-a42d-ebccd49cfd52', // add-noteと異なる } }, ])('の削除は$labelだとできない', async ({ parameters, user, assetion }) => failedApiCall({ - endpoint: '/clips/remove-note', + endpoint: 'clips/remove-note', parameters: { + // @ts-expect-error clipId must not be undefined clipId: aliceClip.id, + // @ts-expect-error noteId must not be undefined noteId: aliceNote.id, ...parameters, }, - user: (user ?? ((): User => alice))(), + user: (user ?? (() => alice))(), }, { status: 400, code: 'INVALID_PARAM', @@ -925,21 +904,22 @@ describe('クリップ', () => { code: 'NO_SUCH_CLIP', id: '1d7645e6-2b6d-4635-b0fe-fe22b0e72e00', } }, - { label: '他人のPrivateなクリップから', user: (): object => bob, assertion: { + { label: '他人のPrivateなクリップから', user: () => bob, assertion: { code: 'NO_SUCH_CLIP', id: '1d7645e6-2b6d-4635-b0fe-fe22b0e72e00', } }, - { label: '未認証でPrivateなクリップから', user: (): undefined => undefined, assertion: { + { label: '未認証でPrivateなクリップから', user: () => undefined, assertion: { code: 'NO_SUCH_CLIP', id: '1d7645e6-2b6d-4635-b0fe-fe22b0e72e00', } }, ])('は$labelだと取得できない', async ({ parameters, user, assertion }) => failedApiCall({ - endpoint: '/clips/notes', + endpoint: 'clips/notes', parameters: { + // @ts-expect-error clipId must not be undefined clipId: aliceClip.id, ...parameters, }, - user: (user ?? ((): User => alice))(), + user: (user ?? (() => alice))(), }, { status: 400, code: 'INVALID_PARAM', diff --git a/packages/backend/test/e2e/drive.ts b/packages/backend/test/e2e/drive.ts index 22ec66e2af..828c5200ef 100644 --- a/packages/backend/test/e2e/drive.ts +++ b/packages/backend/test/e2e/drive.ts @@ -6,22 +6,14 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; -import { MiNote } from '@/models/Note.js'; -import { api, initTestDb, makeStreamCatcher, post, signup, uploadFile } from '../utils.js'; +import { api, makeStreamCatcher, post, signup, uploadFile } from '../utils.js'; import type * as misskey from 'misskey-js'; -import type{ Repository } from 'typeorm' -import type { Packed } from '@/misc/json-schema.js'; - describe('Drive', () => { - let Notes: Repository; - let alice: misskey.entities.SignupResponse; let bob: misskey.entities.SignupResponse; beforeAll(async () => { - const connection = await initTestDb(true); - Notes = connection.getRepository(MiNote); alice = await signup({ username: 'alice' }); bob = await signup({ username: 'bob' }); }, 1000 * 60 * 2); @@ -31,13 +23,13 @@ describe('Drive', () => { const marker = Math.random().toString(); - const url = 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg' + const url = 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg'; const catcher = makeStreamCatcher( alice, 'main', (msg) => msg.type === 'urlUploadFinished' && msg.body.marker === marker, - (msg) => msg.body.file as Packed<'DriveFile'>, + (msg) => msg.body.file, 10 * 1000); const res = await api('drive/files/upload-from-url', { @@ -51,7 +43,7 @@ describe('Drive', () => { assert.strictEqual(res.status, 204); assert.strictEqual(file.name, 'Lenna.jpg'); assert.strictEqual(file.type, 'image/jpeg'); - }) + }); test('ローカルからアップロードできる', async () => { // APIレスポンスを直接使用するので utils.js uploadFile が通過することで成功とする @@ -59,27 +51,27 @@ describe('Drive', () => { const res = await uploadFile(alice, { path: 'Lenna.jpg', name: 'テスト画像' }); assert.strictEqual(res.body?.name, 'テスト画像.jpg'); - assert.strictEqual(res.body?.type, 'image/jpeg'); - }) + assert.strictEqual(res.body.type, 'image/jpeg'); + }); test('添付ノート一覧を取得できる', async () => { - const ids = (await Promise.all([uploadFile(alice), uploadFile(alice), uploadFile(alice)])).map(elm => elm.body!.id) + const ids = (await Promise.all([uploadFile(alice), uploadFile(alice), uploadFile(alice)])).map(elm => elm.body!.id); const note0 = await post(alice, { fileIds: [ids[0]] }); const note1 = await post(alice, { fileIds: [ids[0], ids[1]] }); const attached0 = await api('drive/files/attached-notes', { fileId: ids[0] }, alice); assert.strictEqual(attached0.body.length, 2); - assert.strictEqual(attached0.body[0].id, note1.id) - assert.strictEqual(attached0.body[1].id, note0.id) + assert.strictEqual(attached0.body[0].id, note1.id); + assert.strictEqual(attached0.body[1].id, note0.id); const attached1 = await api('drive/files/attached-notes', { fileId: ids[1] }, alice); assert.strictEqual(attached1.body.length, 1); - assert.strictEqual(attached1.body[0].id, note1.id) + assert.strictEqual(attached1.body[0].id, note1.id); const attached2 = await api('drive/files/attached-notes', { fileId: ids[2] }, alice); - assert.strictEqual(attached2.body.length, 0) - }) + assert.strictEqual(attached2.body.length, 0); + }); test('添付ノート一覧は他の人から見えない', async () => { const file = await uploadFile(alice); @@ -89,7 +81,5 @@ describe('Drive', () => { const res = await api('drive/files/attached-notes', { fileId: file.body!.id }, bob); assert.strictEqual(res.status, 400); assert.strictEqual('error' in res.body, true); - - }) + }); }); - diff --git a/packages/backend/test/e2e/endpoints.ts b/packages/backend/test/e2e/endpoints.ts index d469597805..bc89dc37f4 100644 --- a/packages/backend/test/e2e/endpoints.ts +++ b/packages/backend/test/e2e/endpoints.ts @@ -79,6 +79,7 @@ describe('Endpoints', () => { test('クエリをインジェクションできない', async () => { const res = await api('signin', { username: 'test1', + // @ts-expect-error password must be string password: { $gt: '', }, @@ -103,7 +104,7 @@ describe('Endpoints', () => { const myLocation = '七森中'; const myBirthday = '2000-09-07'; - const res = await api('/i/update', { + const res = await api('i/update', { name: myName, location: myLocation, birthday: myBirthday, @@ -117,7 +118,7 @@ describe('Endpoints', () => { }); test('名前を空白にできる', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { name: ' ', }, alice); assert.strictEqual(res.status, 200); @@ -125,11 +126,11 @@ describe('Endpoints', () => { }); test('誕生日の設定を削除できる', async () => { - await api('/i/update', { + await api('i/update', { birthday: '2000-09-07', }, alice); - const res = await api('/i/update', { + const res = await api('i/update', { birthday: null, }, alice); @@ -139,7 +140,7 @@ describe('Endpoints', () => { }); test('不正な誕生日の形式で怒られる', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { birthday: '2000/09/07', }, alice); assert.strictEqual(res.status, 400); @@ -148,7 +149,7 @@ describe('Endpoints', () => { describe('users/show', () => { test('ユーザーが取得できる', async () => { - const res = await api('/users/show', { + const res = await api('users/show', { userId: alice.id, }, alice); @@ -158,14 +159,14 @@ describe('Endpoints', () => { }); test('ユーザーが存在しなかったら怒る', async () => { - const res = await api('/users/show', { + const res = await api('users/show', { userId: '000000000000000000000000', }); assert.strictEqual(res.status, 404); }); test('間違ったIDで怒られる', async () => { - const res = await api('/users/show', { + const res = await api('users/show', { userId: 'kyoppie', }); assert.strictEqual(res.status, 404); @@ -178,7 +179,7 @@ describe('Endpoints', () => { text: 'test', }); - const res = await api('/notes/show', { + const res = await api('notes/show', { noteId: myPost.id, }, alice); @@ -189,14 +190,14 @@ describe('Endpoints', () => { }); test('投稿が存在しなかったら怒る', async () => { - const res = await api('/notes/show', { + const res = await api('notes/show', { noteId: '000000000000000000000000', }); assert.strictEqual(res.status, 400); }); test('間違ったIDで怒られる', async () => { - const res = await api('/notes/show', { + const res = await api('notes/show', { noteId: 'kyoppie', }); assert.strictEqual(res.status, 400); @@ -207,14 +208,14 @@ describe('Endpoints', () => { test('リアクションできる', async () => { const bobPost = await post(bob, { text: 'hi' }); - const res = await api('/notes/reactions/create', { + const res = await api('notes/reactions/create', { noteId: bobPost.id, reaction: '🚀', }, alice); assert.strictEqual(res.status, 204); - const resNote = await api('/notes/show', { + const resNote = await api('notes/show', { noteId: bobPost.id, }, alice); @@ -225,7 +226,7 @@ describe('Endpoints', () => { test('自分の投稿にもリアクションできる', async () => { const myPost = await post(alice, { text: 'hi' }); - const res = await api('/notes/reactions/create', { + const res = await api('notes/reactions/create', { noteId: myPost.id, reaction: '🚀', }, alice); @@ -236,19 +237,19 @@ describe('Endpoints', () => { test('二重にリアクションすると上書きされる', async () => { const bobPost = await post(bob, { text: 'hi' }); - await api('/notes/reactions/create', { + await api('notes/reactions/create', { noteId: bobPost.id, reaction: '🥰', }, alice); - const res = await api('/notes/reactions/create', { + const res = await api('notes/reactions/create', { noteId: bobPost.id, reaction: '🚀', }, alice); assert.strictEqual(res.status, 204); - const resNote = await api('/notes/show', { + const resNote = await api('notes/show', { noteId: bobPost.id, }, alice); @@ -257,7 +258,7 @@ describe('Endpoints', () => { }); test('存在しない投稿にはリアクションできない', async () => { - const res = await api('/notes/reactions/create', { + const res = await api('notes/reactions/create', { noteId: '000000000000000000000000', reaction: '🚀', }, alice); @@ -266,13 +267,14 @@ describe('Endpoints', () => { }); test('空のパラメータで怒られる', async () => { - const res = await api('/notes/reactions/create', {}, alice); + // @ts-expect-error param must not be empty + const res = await api('notes/reactions/create', {}, alice); assert.strictEqual(res.status, 400); }); test('間違ったIDで怒られる', async () => { - const res = await api('/notes/reactions/create', { + const res = await api('notes/reactions/create', { noteId: 'kyoppie', reaction: '🚀', }, alice); @@ -283,7 +285,7 @@ describe('Endpoints', () => { describe('following/create', () => { test('フォローできる', async () => { - const res = await api('/following/create', { + const res = await api('following/create', { userId: alice.id, }, bob); @@ -301,7 +303,7 @@ describe('Endpoints', () => { }); test('既にフォローしている場合は怒る', async () => { - const res = await api('/following/create', { + const res = await api('following/create', { userId: alice.id, }, bob); @@ -309,7 +311,7 @@ describe('Endpoints', () => { }); test('存在しないユーザーはフォローできない', async () => { - const res = await api('/following/create', { + const res = await api('following/create', { userId: '000000000000000000000000', }, alice); @@ -317,7 +319,7 @@ describe('Endpoints', () => { }); test('自分自身はフォローできない', async () => { - const res = await api('/following/create', { + const res = await api('following/create', { userId: alice.id, }, alice); @@ -325,13 +327,14 @@ describe('Endpoints', () => { }); test('空のパラメータで怒られる', async () => { - const res = await api('/following/create', {}, alice); + // @ts-expect-error params must not be empty + const res = await api('following/create', {}, alice); assert.strictEqual(res.status, 400); }); test('間違ったIDで怒られる', async () => { - const res = await api('/following/create', { + const res = await api('following/create', { userId: 'foo', }, alice); @@ -341,11 +344,11 @@ describe('Endpoints', () => { describe('following/delete', () => { test('フォロー解除できる', async () => { - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const res = await api('/following/delete', { + const res = await api('following/delete', { userId: alice.id, }, bob); @@ -363,7 +366,7 @@ describe('Endpoints', () => { }); test('フォローしていない場合は怒る', async () => { - const res = await api('/following/delete', { + const res = await api('following/delete', { userId: alice.id, }, bob); @@ -371,7 +374,7 @@ describe('Endpoints', () => { }); test('存在しないユーザーはフォロー解除できない', async () => { - const res = await api('/following/delete', { + const res = await api('following/delete', { userId: '000000000000000000000000', }, alice); @@ -379,7 +382,7 @@ describe('Endpoints', () => { }); test('自分自身はフォロー解除できない', async () => { - const res = await api('/following/delete', { + const res = await api('following/delete', { userId: alice.id, }, alice); @@ -387,13 +390,14 @@ describe('Endpoints', () => { }); test('空のパラメータで怒られる', async () => { - const res = await api('/following/delete', {}, alice); + // @ts-expect-error params must not be empty + const res = await api('following/delete', {}, alice); assert.strictEqual(res.status, 400); }); test('間違ったIDで怒られる', async () => { - const res = await api('/following/delete', { + const res = await api('following/delete', { userId: 'kyoppie', }, alice); @@ -403,20 +407,20 @@ describe('Endpoints', () => { describe('channels/search', () => { test('空白検索で一覧を取得できる', async () => { - await api('/channels/create', { + await api('channels/create', { name: 'aaa', description: 'bbb', }, bob); - await api('/channels/create', { + await api('channels/create', { name: 'ccc1', description: 'ddd1', }, bob); - await api('/channels/create', { + await api('channels/create', { name: 'ccc2', description: 'ddd2', }, bob); - const res = await api('/channels/search', { + const res = await api('channels/search', { query: '', }, bob); @@ -425,7 +429,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body.length, 3); }); test('名前のみの検索で名前を検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'aaa', type: 'nameOnly', }, bob); @@ -436,7 +440,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body[0].name, 'aaa'); }); test('名前のみの検索で名前を複数検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'ccc', type: 'nameOnly', }, bob); @@ -446,7 +450,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body.length, 2); }); test('名前のみの検索で説明は検索できない', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'bbb', type: 'nameOnly', }, bob); @@ -456,7 +460,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body.length, 0); }); test('名前と説明の検索で名前を検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'ccc1', }, bob); @@ -466,7 +470,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body[0].name, 'ccc1'); }); test('名前と説明での検索で説明を検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'ddd1', }, bob); @@ -476,7 +480,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body[0].name, 'ccc1'); }); test('名前と説明の検索で名前を複数検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'ccc', }, bob); @@ -485,7 +489,7 @@ describe('Endpoints', () => { assert.strictEqual(res.body.length, 2); }); test('名前と説明での検索で説明を複数検索できる', async () => { - const res = await api('/channels/search', { + const res = await api('channels/search', { query: 'ddd', }, bob); @@ -506,7 +510,7 @@ describe('Endpoints', () => { await uploadFile(alice, { blob: new Blob([new Uint8Array(1024)]), }); - const res = await api('/drive', {}, alice); + const res = await api('drive', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); expect(res.body).toHaveProperty('usage', 1792); @@ -519,7 +523,7 @@ describe('Endpoints', () => { assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'Lenna.jpg'); + assert.strictEqual(res.body!.name, 'Lenna.jpg'); }); test('ファイルに名前を付けられる', async () => { @@ -527,7 +531,7 @@ describe('Endpoints', () => { assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'Belmond.jpg'); + assert.strictEqual(res.body!.name, 'Belmond.jpg'); }); test('ファイルに名前を付けられるが、拡張子は正しいものになる', async () => { @@ -535,11 +539,12 @@ describe('Endpoints', () => { assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'Belmond.png.jpg'); + assert.strictEqual(res.body!.name, 'Belmond.png.jpg'); }); test('ファイル無しで怒られる', async () => { - const res = await api('/drive/files/create', {}, alice); + // @ts-expect-error params must not be empty + const res = await api('drive/files/create', {}, alice); assert.strictEqual(res.status, 400); }); @@ -549,14 +554,14 @@ describe('Endpoints', () => { assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'image.svg'); - assert.strictEqual(res.body.type, 'image/svg+xml'); + assert.strictEqual(res.body!.name, 'image.svg'); + assert.strictEqual(res.body!.type, 'image/svg+xml'); }); for (const type of ['webp', 'avif']) { const mediaType = `image/${type}`; - const getWebpublicType = async (user: any, fileId: string): Promise => { + const getWebpublicType = async (user: misskey.entities.SignupResponse, fileId: string): Promise => { // drive/files/create does not expose webpublicType directly, so get it by posting it const res = await post(user, { text: mediaType, @@ -573,10 +578,10 @@ describe('Endpoints', () => { const res = await uploadFile(alice, { path }); assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.name, path); - assert.strictEqual(res.body.type, mediaType); + assert.strictEqual(res.body!.name, path); + assert.strictEqual(res.body!.type, mediaType); - const webpublicType = await getWebpublicType(alice, res.body.id); + const webpublicType = await getWebpublicType(alice, res.body!.id); assert.strictEqual(webpublicType, 'image/webp'); }); @@ -584,10 +589,10 @@ describe('Endpoints', () => { const path = `without-alpha.${type}`; const res = await uploadFile(alice, { path }); assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.name, path); - assert.strictEqual(res.body.type, mediaType); + assert.strictEqual(res.body!.name, path); + assert.strictEqual(res.body!.type, mediaType); - const webpublicType = await getWebpublicType(alice, res.body.id); + const webpublicType = await getWebpublicType(alice, res.body!.id); assert.strictEqual(webpublicType, 'image/webp'); }); } @@ -598,8 +603,8 @@ describe('Endpoints', () => { const file = (await uploadFile(alice)).body; const newName = 'いちごパスタ.png'; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, name: newName, }, alice); @@ -611,8 +616,8 @@ describe('Endpoints', () => { test('他人のファイルは更新できない', async () => { const file = (await uploadFile(alice)).body; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, name: 'いちごパスタ.png', }, bob); @@ -621,12 +626,12 @@ describe('Endpoints', () => { test('親フォルダを更新できる', async () => { const file = (await uploadFile(alice)).body; - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, folderId: folder.id, }, alice); @@ -638,17 +643,17 @@ describe('Endpoints', () => { test('親フォルダを無しにできる', async () => { const file = (await uploadFile(alice)).body; - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - await api('/drive/files/update', { - fileId: file.id, + await api('drive/files/update', { + fileId: file!.id, folderId: folder.id, }, alice); - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, folderId: null, }, alice); @@ -659,12 +664,12 @@ describe('Endpoints', () => { test('他人のフォルダには入れられない', async () => { const file = (await uploadFile(alice)).body; - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, bob)).body; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, folderId: folder.id, }, alice); @@ -674,8 +679,8 @@ describe('Endpoints', () => { test('存在しないフォルダで怒られる', async () => { const file = (await uploadFile(alice)).body; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, folderId: '000000000000000000000000', }, alice); @@ -685,8 +690,8 @@ describe('Endpoints', () => { test('不正なフォルダIDで怒られる', async () => { const file = (await uploadFile(alice)).body; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, folderId: 'foo', }, alice); @@ -694,7 +699,7 @@ describe('Endpoints', () => { }); test('ファイルが存在しなかったら怒る', async () => { - const res = await api('/drive/files/update', { + const res = await api('drive/files/update', { fileId: '000000000000000000000000', name: 'いちごパスタ.png', }, alice); @@ -706,8 +711,8 @@ describe('Endpoints', () => { const file = (await uploadFile(alice)).body; const newName = ''; - const res = await api('/drive/files/update', { - fileId: file.id, + const res = await api('drive/files/update', { + fileId: file!.id, name: newName, }, alice); @@ -715,7 +720,7 @@ describe('Endpoints', () => { }); test('間違ったIDで怒られる', async () => { - const res = await api('/drive/files/update', { + const res = await api('drive/files/update', { fileId: 'kyoppie', name: 'いちごパスタ.png', }, alice); @@ -726,7 +731,7 @@ describe('Endpoints', () => { describe('drive/folders/create', () => { test('フォルダを作成できる', async () => { - const res = await api('/drive/folders/create', { + const res = await api('drive/folders/create', { name: 'test', }, alice); @@ -738,11 +743,11 @@ describe('Endpoints', () => { describe('drive/folders/update', () => { test('名前を更新できる', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, name: 'new name', }, alice); @@ -753,11 +758,11 @@ describe('Endpoints', () => { }); test('他人のフォルダを更新できない', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, bob)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, name: 'new name', }, alice); @@ -766,14 +771,14 @@ describe('Endpoints', () => { }); test('親フォルダを更新できる', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const parentFolder = (await api('/drive/folders/create', { + const parentFolder = (await api('drive/folders/create', { name: 'parent', }, alice)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: parentFolder.id, }, alice); @@ -784,18 +789,18 @@ describe('Endpoints', () => { }); test('親フォルダを無しに更新できる', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const parentFolder = (await api('/drive/folders/create', { + const parentFolder = (await api('drive/folders/create', { name: 'parent', }, alice)).body; - await api('/drive/folders/update', { + await api('drive/folders/update', { folderId: folder.id, parentId: parentFolder.id, }, alice); - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: null, }, alice); @@ -806,14 +811,14 @@ describe('Endpoints', () => { }); test('他人のフォルダを親フォルダに設定できない', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const parentFolder = (await api('/drive/folders/create', { + const parentFolder = (await api('drive/folders/create', { name: 'parent', }, bob)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: parentFolder.id, }, alice); @@ -822,18 +827,18 @@ describe('Endpoints', () => { }); test('フォルダが循環するような構造にできない', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const parentFolder = (await api('/drive/folders/create', { + const parentFolder = (await api('drive/folders/create', { name: 'parent', }, alice)).body; - await api('/drive/folders/update', { + await api('drive/folders/update', { folderId: parentFolder.id, parentId: folder.id, }, alice); - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: parentFolder.id, }, alice); @@ -842,25 +847,25 @@ describe('Endpoints', () => { }); test('フォルダが循環するような構造にできない(再帰的)', async () => { - const folderA = (await api('/drive/folders/create', { + const folderA = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const folderB = (await api('/drive/folders/create', { + const folderB = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const folderC = (await api('/drive/folders/create', { + const folderC = (await api('drive/folders/create', { name: 'test', }, alice)).body; - await api('/drive/folders/update', { + await api('drive/folders/update', { folderId: folderB.id, parentId: folderA.id, }, alice); - await api('/drive/folders/update', { + await api('drive/folders/update', { folderId: folderC.id, parentId: folderB.id, }, alice); - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folderA.id, parentId: folderC.id, }, alice); @@ -869,11 +874,11 @@ describe('Endpoints', () => { }); test('フォルダが循環するような構造にできない(自身)', async () => { - const folderA = (await api('/drive/folders/create', { + const folderA = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folderA.id, parentId: folderA.id, }, alice); @@ -882,11 +887,11 @@ describe('Endpoints', () => { }); test('存在しない親フォルダを設定できない', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: '000000000000000000000000', }, alice); @@ -895,11 +900,11 @@ describe('Endpoints', () => { }); test('不正な親フォルダIDで怒られる', async () => { - const folder = (await api('/drive/folders/create', { + const folder = (await api('drive/folders/create', { name: 'test', }, alice)).body; - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: folder.id, parentId: 'foo', }, alice); @@ -908,7 +913,7 @@ describe('Endpoints', () => { }); test('存在しないフォルダを更新できない', async () => { - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: '000000000000000000000000', }, alice); @@ -916,7 +921,7 @@ describe('Endpoints', () => { }); test('不正なフォルダIDで怒られる', async () => { - const res = await api('/drive/folders/update', { + const res = await api('drive/folders/update', { folderId: 'foo', }, alice); @@ -937,7 +942,7 @@ describe('Endpoints', () => { visibleUserIds: [alice.id], }); - const res = await api('/notes/replies', { + const res = await api('notes/replies', { noteId: alicePost.id, }, carol); @@ -949,7 +954,7 @@ describe('Endpoints', () => { describe('notes/timeline', () => { test('フォロワー限定投稿が含まれる', async () => { - await api('/following/create', { + await api('following/create', { userId: carol.id, }, dave); @@ -958,7 +963,7 @@ describe('Endpoints', () => { visibility: 'followers', }); - const res = await api('/notes/timeline', {}, dave); + const res = await api('notes/timeline', {}, dave); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -979,12 +984,12 @@ describe('Endpoints', () => { test('他者に関するメモを更新できる', async () => { const memo = '10月まで低浮上とのこと。'; - const res1 = await api('/users/update-memo', { + const res1 = await api('users/update-memo', { memo, userId: bob.id, }, alice); - const res2 = await api('/users/show', { + const res2 = await api('users/show', { userId: bob.id, }, alice); assert.strictEqual(res1.status, 204); @@ -994,12 +999,12 @@ describe('Endpoints', () => { test('自分に関するメモを更新できる', async () => { const memo = 'チケットを月末までに買う。'; - const res1 = await api('/users/update-memo', { + const res1 = await api('users/update-memo', { memo, userId: alice.id, }, alice); - const res2 = await api('/users/show', { + const res2 = await api('users/show', { userId: alice.id, }, alice); assert.strictEqual(res1.status, 204); @@ -1009,17 +1014,17 @@ describe('Endpoints', () => { test('メモを削除できる', async () => { const memo = '10月まで低浮上とのこと。'; - await api('/users/update-memo', { + await api('users/update-memo', { memo, userId: bob.id, }, alice); - await api('/users/update-memo', { + await api('users/update-memo', { memo: '', userId: bob.id, }, alice); - const res = await api('/users/show', { + const res = await api('users/show', { userId: bob.id, }, alice); @@ -1032,21 +1037,21 @@ describe('Endpoints', () => { const memoCarolToBob = '例の件について今度問いただす。'; await Promise.all([ - api('/users/update-memo', { + api('users/update-memo', { memo: memoAliceToBob, userId: bob.id, }, alice), - api('/users/update-memo', { + api('users/update-memo', { memo: memoCarolToBob, userId: bob.id, }, carol), ]); const [resAlice, resCarol] = await Promise.all([ - api('/users/show', { + api('users/show', { userId: bob.id, }, alice), - api('/users/show', { + api('users/show', { userId: bob.id, }, carol), ]); diff --git a/packages/backend/test/e2e/exports.ts b/packages/backend/test/e2e/exports.ts index eb03935a2a..80a5331a6d 100644 --- a/packages/backend/test/e2e/exports.ts +++ b/packages/backend/test/e2e/exports.ts @@ -18,7 +18,7 @@ describe('export-clips', () => { // XXX: Any better way to get the result? async function pollFirstDriveFile() { while (true) { - const files = (await api('/drive/files', {}, alice)).body; + const files = (await api('drive/files', {}, alice)).body; if (!files.length) { await new Promise(r => setTimeout(r, 100)); continue; @@ -26,7 +26,7 @@ describe('export-clips', () => { if (files.length > 1) { throw new Error('Too many files?'); } - const file = (await api('/drive/files/show', { fileId: files[0].id }, alice)).body; + const file = (await api('drive/files/show', { fileId: files[0].id }, alice)).body; const res = await fetch(new URL(new URL(file.url).pathname, `http://127.0.0.1:${port}`)); return await res.json(); } @@ -44,16 +44,16 @@ describe('export-clips', () => { beforeEach(async () => { // Clean all clips and files of alice - const clips = (await api('/clips/list', {}, alice)).body; + const clips = (await api('clips/list', {}, alice)).body; for (const clip of clips) { - const res = await api('/clips/delete', { clipId: clip.id }, alice); + const res = await api('clips/delete', { clipId: clip.id }, alice); if (res.status !== 204) { throw new Error('Failed to delete clip'); } } - const files = (await api('/drive/files', {}, alice)).body; + const files = (await api('drive/files', {}, alice)).body; for (const file of files) { - const res = await api('/drive/files/delete', { fileId: file.id }, alice); + const res = await api('drive/files/delete', { fileId: file.id }, alice); if (res.status !== 204) { throw new Error('Failed to delete file'); } @@ -61,13 +61,13 @@ describe('export-clips', () => { }); test('basic export', async () => { - let res = await api('/clips/create', { + let res = await api('clips/create', { name: 'foo', description: 'bar', }, alice); assert.strictEqual(res.status, 200); - res = await api('/i/export-clips', {}, alice); + res = await api('i/export-clips', {}, alice); assert.strictEqual(res.status, 204); const exported = await pollFirstDriveFile(); @@ -77,7 +77,7 @@ describe('export-clips', () => { }); test('export with notes', async () => { - let res = await api('/clips/create', { + let res = await api('clips/create', { name: 'foo', description: 'bar', }, alice); @@ -96,14 +96,14 @@ describe('export-clips', () => { }); for (const note of [note1, note2]) { - res = await api('/clips/add-note', { + res = await api('clips/add-note', { clipId: clip.id, noteId: note.id, }, alice); assert.strictEqual(res.status, 204); } - res = await api('/i/export-clips', {}, alice); + res = await api('i/export-clips', {}, alice); assert.strictEqual(res.status, 204); const exported = await pollFirstDriveFile(); @@ -116,14 +116,14 @@ describe('export-clips', () => { }); test('multiple clips', async () => { - let res = await api('/clips/create', { + let res = await api('clips/create', { name: 'kawaii', description: 'kawaii', }, alice); assert.strictEqual(res.status, 200); const clip1 = res.body; - res = await api('/clips/create', { + res = await api('clips/create', { name: 'yuri', description: 'yuri', }, alice); @@ -138,19 +138,19 @@ describe('export-clips', () => { text: 'baz2', }); - res = await api('/clips/add-note', { + res = await api('clips/add-note', { clipId: clip1.id, noteId: note1.id, }, alice); assert.strictEqual(res.status, 204); - res = await api('/clips/add-note', { + res = await api('clips/add-note', { clipId: clip2.id, noteId: note2.id, }, alice); assert.strictEqual(res.status, 204); - res = await api('/i/export-clips', {}, alice); + res = await api('i/export-clips', {}, alice); assert.strictEqual(res.status, 204); const exported = await pollFirstDriveFile(); @@ -163,7 +163,7 @@ describe('export-clips', () => { }); test('Clipping other user\'s note', async () => { - let res = await api('/clips/create', { + let res = await api('clips/create', { name: 'kawaii', description: 'kawaii', }, alice); @@ -175,13 +175,13 @@ describe('export-clips', () => { visibility: 'followers', }); - res = await api('/clips/add-note', { + res = await api('clips/add-note', { clipId: clip.id, noteId: note.id, }, alice); assert.strictEqual(res.status, 204); - res = await api('/i/export-clips', {}, alice); + res = await api('i/export-clips', {}, alice); assert.strictEqual(res.status, 204); const exported = await pollFirstDriveFile(); diff --git a/packages/backend/test/e2e/fetch-resource.ts b/packages/backend/test/e2e/fetch-resource.ts index 74033b7dff..4851ed14be 100644 --- a/packages/backend/test/e2e/fetch-resource.ts +++ b/packages/backend/test/e2e/fetch-resource.ts @@ -23,13 +23,13 @@ const JSON_UTF8 = 'application/json; charset=utf-8'; describe('Webリソース', () => { let alice: misskey.entities.SignupResponse; - let aliceUploadedFile: any; - let alicesPost: any; - let alicePage: any; - let alicePlay: any; - let aliceClip: any; - let aliceGalleryPost: any; - let aliceChannel: any; + let aliceUploadedFile: misskey.entities.DriveFile | null; + let alicesPost: misskey.entities.Note; + let alicePage: misskey.entities.Page; + let alicePlay: misskey.entities.Flash; + let aliceClip: misskey.entities.Clip; + let aliceGalleryPost: misskey.entities.GalleryPost; + let aliceChannel: misskey.entities.Channel; let bob: misskey.entities.SignupResponse; @@ -77,7 +77,7 @@ describe('Webリソース', () => { beforeAll(async () => { alice = await signup({ username: 'alice' }); - aliceUploadedFile = await uploadFile(alice); + aliceUploadedFile = (await uploadFile(alice)).body; alicesPost = await post(alice, { text: 'test', }); @@ -85,7 +85,7 @@ describe('Webリソース', () => { alicePlay = await play(alice, {}); aliceClip = await clip(alice, {}); aliceGalleryPost = await galleryPost(alice, { - fileIds: [aliceUploadedFile.body.id], + fileIds: [aliceUploadedFile!.id], }); aliceChannel = await channel(alice, {}); diff --git a/packages/backend/test/e2e/ff-visibility.ts b/packages/backend/test/e2e/ff-visibility.ts index b59dd8824a..5d0c70a3c2 100644 --- a/packages/backend/test/e2e/ff-visibility.ts +++ b/packages/backend/test/e2e/ff-visibility.ts @@ -19,15 +19,15 @@ describe('FF visibility', () => { }, 1000 * 60 * 2); test('followingVisibility, followersVisibility がともに public なユーザーのフォロー/フォロワーを誰でも見れる', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); @@ -39,36 +39,36 @@ describe('FF visibility', () => { test('followingVisibility が public であれば followersVisibility の設定に関わらずユーザーのフォローを誰でも見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); @@ -78,36 +78,36 @@ describe('FF visibility', () => { test('followersVisibility が public であれば followingVisibility の設定に関わらずユーザーのフォロワーを誰でも見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'public', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'public', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'public', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); @@ -116,15 +116,15 @@ describe('FF visibility', () => { }); test('followingVisibility, followersVisibility がともに followers なユーザーのフォロー/フォロワーを自分で見れる', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); @@ -136,36 +136,36 @@ describe('FF visibility', () => { test('followingVisibility が followers なユーザーのフォローを followersVisibility の設定に関わらず自分で見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); @@ -175,36 +175,36 @@ describe('FF visibility', () => { test('followersVisibility が followers なユーザーのフォロワーを followingVisibility の設定に関わらず自分で見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); @@ -213,15 +213,15 @@ describe('FF visibility', () => { }); test('followingVisibility, followersVisibility がともに followers なユーザーのフォロー/フォロワーを非フォロワーが見れない', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); @@ -231,34 +231,34 @@ describe('FF visibility', () => { test('followingVisibility が followers なユーザーのフォローを followersVisibility の設定に関わらず非フォロワーが見れない', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); @@ -267,34 +267,34 @@ describe('FF visibility', () => { test('followersVisibility が followers なユーザーのフォロワーを followingVisibility の設定に関わらず非フォロワーが見れない', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'followers', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); @@ -302,19 +302,19 @@ describe('FF visibility', () => { }); test('followingVisibility, followersVisibility がともに followers なユーザーのフォロー/フォロワーをフォロワーが見れる', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); @@ -326,45 +326,45 @@ describe('FF visibility', () => { test('followingVisibility が followers なユーザーのフォローを followersVisibility の設定に関わらずフォロワーが見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'public', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'private', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 200); @@ -374,45 +374,45 @@ describe('FF visibility', () => { test('followersVisibility が followers なユーザーのフォロワーを followingVisibility の設定に関わらずフォロワーが見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'followers', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'followers', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'followers', }, alice); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 200); @@ -421,15 +421,15 @@ describe('FF visibility', () => { }); test('followingVisibility, followersVisibility がともに private なユーザーのフォロー/フォロワーを自分で見れる', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); @@ -441,36 +441,36 @@ describe('FF visibility', () => { test('followingVisibility が private なユーザーのフォローを followersVisibility の設定に関わらず自分で見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); assert.strictEqual(Array.isArray(followingRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(followingRes.status, 200); @@ -480,36 +480,36 @@ describe('FF visibility', () => { test('followersVisibility が private なユーザーのフォロワーを followingVisibility の設定に関わらず自分で見れる', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); assert.strictEqual(Array.isArray(followersRes.body), true); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, alice); assert.strictEqual(followersRes.status, 200); @@ -518,15 +518,15 @@ describe('FF visibility', () => { }); test('followingVisibility, followersVisibility がともに private なユーザーのフォロー/フォロワーを他人が見れない', async () => { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); @@ -536,34 +536,34 @@ describe('FF visibility', () => { test('followingVisibility が private なユーザーのフォローを followersVisibility の設定に関わらず他人が見れない', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'public', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'followers', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followingRes = await api('/users/following', { + const followingRes = await api('users/following', { userId: alice.id, }, bob); assert.strictEqual(followingRes.status, 400); @@ -572,34 +572,34 @@ describe('FF visibility', () => { test('followersVisibility が private なユーザーのフォロワーを followingVisibility の設定に関わらず他人が見れない', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', followersVisibility: 'private', }, alice); - const followersRes = await api('/users/followers', { + const followersRes = await api('users/followers', { userId: alice.id, }, bob); assert.strictEqual(followersRes.status, 400); @@ -609,7 +609,7 @@ describe('FF visibility', () => { describe('AP', () => { test('followingVisibility が public 以外ならばAPからはフォローを取得できない', async () => { { - await api('/i/update', { + await api('i/update', { followingVisibility: 'public', }, alice); @@ -617,7 +617,7 @@ describe('FF visibility', () => { assert.strictEqual(followingRes.status, 200); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'followers', }, alice); @@ -625,7 +625,7 @@ describe('FF visibility', () => { assert.strictEqual(followingRes.status, 403); } { - await api('/i/update', { + await api('i/update', { followingVisibility: 'private', }, alice); @@ -636,7 +636,7 @@ describe('FF visibility', () => { test('followersVisibility が public 以外ならばAPからはフォロワーを取得できない', async () => { { - await api('/i/update', { + await api('i/update', { followersVisibility: 'public', }, alice); @@ -644,7 +644,7 @@ describe('FF visibility', () => { assert.strictEqual(followersRes.status, 200); } { - await api('/i/update', { + await api('i/update', { followersVisibility: 'followers', }, alice); @@ -652,7 +652,7 @@ describe('FF visibility', () => { assert.strictEqual(followersRes.status, 403); } { - await api('/i/update', { + await api('i/update', { followersVisibility: 'private', }, alice); diff --git a/packages/backend/test/e2e/move.ts b/packages/backend/test/e2e/move.ts index f6417e39b5..35050130dc 100644 --- a/packages/backend/test/e2e/move.ts +++ b/packages/backend/test/e2e/move.ts @@ -55,7 +55,7 @@ describe('Account Move', () => { }, 1000 * 10); test('Able to create an alias', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`], }, bob); @@ -67,7 +67,7 @@ describe('Account Move', () => { }); test('Able to create a local alias without hostname', async () => { - await api('/i/update', { + await api('i/update', { alsoKnownAs: ['@alice'], }, bob); @@ -77,7 +77,7 @@ describe('Account Move', () => { }); test('Able to create a local alias without @', async () => { - await api('/i/update', { + await api('i/update', { alsoKnownAs: ['alice'], }, bob); @@ -87,7 +87,7 @@ describe('Account Move', () => { }); test('Able to set remote user (but may fail)', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { alsoKnownAs: ['@syuilo@example.com'], }, bob); @@ -97,7 +97,7 @@ describe('Account Move', () => { }); test('Unable to add duplicated aliases to alsoKnownAs', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`, `@alice@${url.hostname}`], }, bob); @@ -107,7 +107,7 @@ describe('Account Move', () => { }); test('Unable to add itself', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { alsoKnownAs: [`@bob@${url.hostname}`], }, bob); @@ -117,7 +117,7 @@ describe('Account Move', () => { }); test('Unable to add a nonexisting local account to alsoKnownAs', async () => { - const res1 = await api('/i/update', { + const res1 = await api('i/update', { alsoKnownAs: [`@nonexist@${url.hostname}`], }, bob); @@ -125,7 +125,7 @@ describe('Account Move', () => { assert.strictEqual(res1.body.error.code, 'NO_SUCH_USER'); assert.strictEqual(res1.body.error.id, 'fcd2eef9-a9b2-4c4f-8624-038099e90aa5'); - const res2 = await api('/i/update', { + const res2 = await api('i/update', { alsoKnownAs: ['@alice', 'nonexist'], }, bob); @@ -135,7 +135,7 @@ describe('Account Move', () => { }); test('Able to add two existing local account to alsoKnownAs', async () => { - await api('/i/update', { + await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`, `@carol@${url.hostname}`], }, bob); @@ -146,10 +146,10 @@ describe('Account Move', () => { }); test('Able to properly overwrite alsoKnownAs', async () => { - await api('/i/update', { + await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`], }, bob); - await api('/i/update', { + await api('i/update', { alsoKnownAs: [`@carol@${url.hostname}`, `@dave@${url.hostname}`], }, bob); @@ -164,79 +164,78 @@ describe('Account Move', () => { let antennaId = ''; beforeAll(async () => { - await api('/i/update', { + await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`], }, root); - const listRoot = await api('/users/lists/create', { + const listRoot = await api('users/lists/create', { name: secureRndstr(8), }, root); - await api('/users/lists/push', { + await api('users/lists/push', { listId: listRoot.body.id, userId: alice.id, }, root); - await api('/following/create', { + await api('following/create', { userId: root.id, }, alice); - await api('/following/create', { + await api('following/create', { userId: eve.id, }, alice); - const antenna = await api('/antennas/create', { + const antenna = await api('antennas/create', { name: secureRndstr(8), src: 'home', - keywords: [secureRndstr(8)], + keywords: [[secureRndstr(8)]], excludeKeywords: [], users: [], caseSensitive: false, localOnly: false, withReplies: false, withFile: false, - notify: false, }, alice); antennaId = antenna.body.id; - await api('/i/update', { + await api('i/update', { alsoKnownAs: [`@alice@${url.hostname}`], }, bob); - await api('/following/create', { + await api('following/create', { userId: alice.id, }, carol); - await api('/mute/create', { + await api('mute/create', { userId: alice.id, }, dave); - await api('/blocking/create', { + await api('blocking/create', { userId: alice.id, }, dave); - await api('/following/create', { + await api('following/create', { userId: eve.id, }, dave); - await api('/following/create', { + await api('following/create', { userId: dave.id, }, eve); - const listEve = await api('/users/lists/create', { + const listEve = await api('users/lists/create', { name: secureRndstr(8), }, eve); - await api('/users/lists/push', { + await api('users/lists/push', { listId: listEve.body.id, userId: bob.id, }, eve); - await api('/i/update', { + await api('i/update', { isLocked: true, }, frank); - await api('/following/create', { + await api('following/create', { userId: frank.id, }, alice); - await api('/following/requests/accept', { + await api('following/requests/accept', { userId: alice.id, }, frank); }, 1000 * 10); test('Prohibit the root account from moving', async () => { - const res = await api('/i/move', { + const res = await api('i/move', { moveToAccount: `@bob@${url.hostname}`, }, root); @@ -246,7 +245,7 @@ describe('Account Move', () => { }); test('Unable to move to a nonexisting local account', async () => { - const res = await api('/i/move', { + const res = await api('i/move', { moveToAccount: `@nonexist@${url.hostname}`, }, alice); @@ -256,7 +255,7 @@ describe('Account Move', () => { }); test('Unable to move if alsoKnownAs is invalid', async () => { - const res = await api('/i/move', { + const res = await api('i/move', { moveToAccount: `@carol@${url.hostname}`, }, alice); @@ -266,7 +265,7 @@ describe('Account Move', () => { }); test('Relationships have been properly migrated', async () => { - const move = await api('/i/move', { + const move = await api('i/move', { moveToAccount: `@bob@${url.hostname}`, }, alice); @@ -275,13 +274,13 @@ describe('Account Move', () => { await sleep(1000 * 3); // wait for jobs to finish // Unfollow delayed? - const aliceFollowings = await api('/users/following', { + const aliceFollowings = await api('users/following', { userId: alice.id, }, alice); assert.strictEqual(aliceFollowings.status, 200); assert.strictEqual(aliceFollowings.body.length, 3); - const carolFollowings = await api('/users/following', { + const carolFollowings = await api('users/following', { userId: carol.id, }, carol); assert.strictEqual(carolFollowings.status, 200); @@ -289,25 +288,25 @@ describe('Account Move', () => { assert.strictEqual(carolFollowings.body[0].followeeId, bob.id); assert.strictEqual(carolFollowings.body[1].followeeId, alice.id); - const blockings = await api('/blocking/list', {}, dave); + const blockings = await api('blocking/list', {}, dave); assert.strictEqual(blockings.status, 200); assert.strictEqual(blockings.body.length, 2); assert.strictEqual(blockings.body[0].blockeeId, bob.id); assert.strictEqual(blockings.body[1].blockeeId, alice.id); - const mutings = await api('/mute/list', {}, dave); + const mutings = await api('mute/list', {}, dave); assert.strictEqual(mutings.status, 200); assert.strictEqual(mutings.body.length, 2); assert.strictEqual(mutings.body[0].muteeId, bob.id); assert.strictEqual(mutings.body[1].muteeId, alice.id); - const rootLists = await api('/users/lists/list', {}, root); + const rootLists = await api('users/lists/list', {}, root); assert.strictEqual(rootLists.status, 200); assert.strictEqual(rootLists.body[0].userIds.length, 2); assert.ok(rootLists.body[0].userIds.find((id: string) => id === bob.id)); assert.ok(rootLists.body[0].userIds.find((id: string) => id === alice.id)); - const eveLists = await api('/users/lists/list', {}, eve); + const eveLists = await api('users/lists/list', {}, eve); assert.strictEqual(eveLists.status, 200); assert.strictEqual(eveLists.body[0].userIds.length, 1); assert.ok(eveLists.body[0].userIds.find((id: string) => id === bob.id)); @@ -315,13 +314,13 @@ describe('Account Move', () => { test('A locked account automatically accept the follow request if it had already accepted the old account.', async () => { await successfulApiCall({ - endpoint: '/following/create', + endpoint: 'following/create', parameters: { userId: frank.id, }, user: bob, }); - const followers = await api('/users/followers', { + const followers = await api('users/followers', { userId: frank.id, }, frank); @@ -333,7 +332,7 @@ describe('Account Move', () => { test('Unfollowed after 10 sec (24 hours in production).', async () => { await sleep(1000 * 8); - const following = await api('/users/following', { + const following = await api('users/following', { userId: alice.id, }, alice); @@ -342,7 +341,7 @@ describe('Account Move', () => { }); test('Unable to move if the destination account has already moved.', async () => { - const res = await api('/i/move', { + const res = await api('i/move', { moveToAccount: `@alice@${url.hostname}`, }, bob); @@ -352,7 +351,7 @@ describe('Account Move', () => { }); test('Follow and follower counts are properly adjusted', async () => { - await api('/following/create', { + await api('following/create', { userId: alice.id, }, eve); const newAlice = await Users.findOneByOrFail({ id: alice.id }); @@ -365,7 +364,7 @@ describe('Account Move', () => { assert.strictEqual(newEve.followingCount, 1); assert.strictEqual(newEve.followersCount, 1); - await api('/following/delete', { + await api('following/delete', { userId: alice.id, }, eve); newEve = await Users.findOneByOrFail({ id: eve.id }); @@ -374,49 +373,49 @@ describe('Account Move', () => { }); test.each([ - '/antennas/create', - '/channels/create', - '/channels/favorite', - '/channels/follow', - '/channels/unfavorite', - '/channels/unfollow', - '/clips/add-note', - '/clips/create', - '/clips/favorite', - '/clips/remove-note', - '/clips/unfavorite', - '/clips/update', - '/drive/files/upload-from-url', - '/flash/create', - '/flash/like', - '/flash/unlike', - '/flash/update', - '/following/create', - '/gallery/posts/create', - '/gallery/posts/like', - '/gallery/posts/unlike', - '/gallery/posts/update', - '/i/claim-achievement', - '/i/move', - '/i/import-blocking', - '/i/import-following', - '/i/import-muting', - '/i/import-user-lists', - '/i/pin', - '/mute/create', - '/notes/create', - '/notes/favorites/create', - '/notes/polls/vote', - '/notes/reactions/create', - '/pages/create', - '/pages/like', - '/pages/unlike', - '/pages/update', - '/renote-mute/create', - '/users/lists/create', - '/users/lists/pull', - '/users/lists/push', - ])('Prohibit access after moving: %s', async (endpoint) => { + 'antennas/create', + 'channels/create', + 'channels/favorite', + 'channels/follow', + 'channels/unfavorite', + 'channels/unfollow', + 'clips/add-note', + 'clips/create', + 'clips/favorite', + 'clips/remove-note', + 'clips/unfavorite', + 'clips/update', + 'drive/files/upload-from-url', + 'flash/create', + 'flash/like', + 'flash/unlike', + 'flash/update', + 'following/create', + 'gallery/posts/create', + 'gallery/posts/like', + 'gallery/posts/unlike', + 'gallery/posts/update', + 'i/claim-achievement', + 'i/move', + 'i/import-blocking', + 'i/import-following', + 'i/import-muting', + 'i/import-user-lists', + 'i/pin', + 'mute/create', + 'notes/create', + 'notes/favorites/create', + 'notes/polls/vote', + 'notes/reactions/create', + 'pages/create', + 'pages/like', + 'pages/unlike', + 'pages/update', + 'renote-mute/create', + 'users/lists/create', + 'users/lists/pull', + 'users/lists/push', + ] as const)('Prohibit access after moving: %s', async (endpoint) => { const res = await api(endpoint, {}, alice); assert.strictEqual(res.status, 403); assert.strictEqual(res.body.error.code, 'YOUR_ACCOUNT_MOVED'); @@ -424,18 +423,17 @@ describe('Account Move', () => { }); test('Prohibit access after moving: /antennas/update', async () => { - const res = await api('/antennas/update', { + const res = await api('antennas/update', { antennaId, name: secureRndstr(8), src: 'users', - keywords: [secureRndstr(8)], + keywords: [[secureRndstr(8)]], excludeKeywords: [], users: [eve.id], caseSensitive: false, localOnly: false, withReplies: false, withFile: false, - notify: false, }, alice); assert.strictEqual(res.status, 403); @@ -447,12 +445,12 @@ describe('Account Move', () => { const res = await uploadFile(alice); assert.strictEqual(res.status, 403); - assert.strictEqual(res.body.error.code, 'YOUR_ACCOUNT_MOVED'); - assert.strictEqual(res.body.error.id, '56f20ec9-fd06-4fa5-841b-edd6d7d4fa31'); + assert.strictEqual((res.body! as any as { error: misskey.api.APIError }).error.code, 'YOUR_ACCOUNT_MOVED'); + assert.strictEqual((res.body! as any as { error: misskey.api.APIError }).error.id, '56f20ec9-fd06-4fa5-841b-edd6d7d4fa31'); }); test('Prohibit updating alsoKnownAs after moving', async () => { - const res = await api('/i/update', { + const res = await api('i/update', { alsoKnownAs: [`@eve@${url.hostname}`], }, alice); diff --git a/packages/backend/test/e2e/mute.ts b/packages/backend/test/e2e/mute.ts index 1d28e07b7d..0e52c5decc 100644 --- a/packages/backend/test/e2e/mute.ts +++ b/packages/backend/test/e2e/mute.ts @@ -19,21 +19,31 @@ describe('Mute', () => { alice = await signup({ username: 'alice' }); bob = await signup({ username: 'bob' }); carol = await signup({ username: 'carol' }); + + // Mute: alice ==> carol + await api('mute/create', { + userId: carol.id, + }, alice); }, 1000 * 60 * 2); test('ミュート作成', async () => { - const res = await api('/mute/create', { - userId: carol.id, + const res = await api('mute/create', { + userId: bob.id, }, alice); assert.strictEqual(res.status, 204); + + // 単体でも走らせられるように副作用消す + await api('mute/delete', { + userId: bob.id, + }, alice); }); test('「自分宛ての投稿」にミュートしているユーザーの投稿が含まれない', async () => { const bobNote = await post(bob, { text: '@alice hi' }); const carolNote = await post(carol, { text: '@alice hi' }); - const res = await api('/notes/mentions', {}, alice); + const res = await api('notes/mentions', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -43,11 +53,11 @@ describe('Mute', () => { test('ミュートしているユーザーからメンションされても、hasUnreadMentions が true にならない', async () => { // 状態リセット - await api('/i/read-all-unread-notes', {}, alice); + await api('i/read-all-unread-notes', {}, alice); await post(carol, { text: '@alice hi' }); - const res = await api('/i', {}, alice); + const res = await api('i', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(res.body.hasUnreadMentions, false); @@ -55,7 +65,7 @@ describe('Mute', () => { test('ミュートしているユーザーからメンションされても、ストリームに unreadMention イベントが流れてこない', async () => { // 状態リセット - await api('/i/read-all-unread-notes', {}, alice); + await api('i/read-all-unread-notes', {}, alice); const fired = await waitFire(alice, 'main', () => post(carol, { text: '@alice hi' }), msg => msg.type === 'unreadMention'); @@ -64,8 +74,8 @@ describe('Mute', () => { test('ミュートしているユーザーからメンションされても、ストリームに unreadNotification イベントが流れてこない', async () => { // 状態リセット - await api('/i/read-all-unread-notes', {}, alice); - await api('/notifications/mark-all-as-read', {}, alice); + await api('i/read-all-unread-notes', {}, alice); + await api('notifications/mark-all-as-read', {}, alice); const fired = await waitFire(alice, 'main', () => post(carol, { text: '@alice hi' }), msg => msg.type === 'unreadNotification'); @@ -78,7 +88,7 @@ describe('Mute', () => { const bobNote = await post(bob, { text: 'hi' }); const carolNote = await post(carol, { text: 'hi' }); - const res = await api('/notes/local-timeline', {}, alice); + const res = await api('notes/local-timeline', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -94,7 +104,7 @@ describe('Mute', () => { renoteId: carolNote.id, }); - const res = await api('/notes/local-timeline', {}, alice); + const res = await api('notes/local-timeline', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -110,7 +120,7 @@ describe('Mute', () => { await react(bob, aliceNote, 'like'); await react(carol, aliceNote, 'like'); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -123,7 +133,7 @@ describe('Mute', () => { await post(bob, { text: '@alice hi', replyId: aliceNote.id }); await post(carol, { text: '@alice hi', replyId: aliceNote.id }); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -137,7 +147,7 @@ describe('Mute', () => { await post(bob, { text: '@alice hi' }); await post(carol, { text: '@alice hi' }); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -151,7 +161,7 @@ describe('Mute', () => { await post(bob, { text: 'hi', renoteId: aliceNote.id }); await post(carol, { text: 'hi', renoteId: aliceNote.id }); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -165,7 +175,7 @@ describe('Mute', () => { await post(bob, { renoteId: aliceNote.id }); await post(carol, { renoteId: aliceNote.id }); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -175,30 +185,36 @@ describe('Mute', () => { }); test('通知にミュートしているユーザーからのフォロー通知が含まれない', async () => { - await api('/i/follow', { userId: alice.id }, bob); - await api('/i/follow', { userId: alice.id }, carol); + await api('following/create', { userId: alice.id }, bob); + await api('following/create', { userId: alice.id }, carol); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === bob.id), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === carol.id), false); + + await api('following/delete', { userId: alice.id }, bob); + await api('following/delete', { userId: alice.id }, carol); }); test('通知にミュートしているユーザーからのフォローリクエストが含まれない', async () => { - await api('/i/update/', { isLocked: true }, alice); - await api('/following/create', { userId: alice.id }, bob); - await api('/following/create', { userId: alice.id }, carol); + await api('i/update', { isLocked: true }, alice); + await api('following/create', { userId: alice.id }, bob); + await api('following/create', { userId: alice.id }, carol); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === bob.id), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === carol.id), false); + + await api('following/delete', { userId: alice.id }, bob); + await api('following/delete', { userId: alice.id }, carol); }); }); @@ -208,7 +224,7 @@ describe('Mute', () => { await react(bob, aliceNote, 'like'); await react(carol, aliceNote, 'like'); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -220,7 +236,7 @@ describe('Mute', () => { await post(bob, { text: '@alice hi', replyId: aliceNote.id }); await post(carol, { text: '@alice hi', replyId: aliceNote.id }); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -234,7 +250,7 @@ describe('Mute', () => { await post(bob, { text: '@alice hi' }); await post(carol, { text: '@alice hi' }); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -248,7 +264,7 @@ describe('Mute', () => { await post(bob, { text: 'hi', renoteId: aliceNote.id }); await post(carol, { text: 'hi', renoteId: aliceNote.id }); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -262,7 +278,7 @@ describe('Mute', () => { await post(bob, { renoteId: aliceNote.id }); await post(carol, { renoteId: aliceNote.id }); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -272,24 +288,27 @@ describe('Mute', () => { }); test('通知にミュートしているユーザーからのフォロー通知が含まれない', async () => { - await api('/i/follow', { userId: alice.id }, bob); - await api('/i/follow', { userId: alice.id }, carol); + await api('following/create', { userId: alice.id }, bob); + await api('following/create', { userId: alice.id }, carol); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === bob.id), true); assert.strictEqual(res.body.some((notification: any) => notification.userId === carol.id), false); + + await api('following/delete', { userId: alice.id }, bob); + await api('following/delete', { userId: alice.id }, carol); }); test('通知にミュートしているユーザーからのフォローリクエストが含まれない', async () => { - await api('/i/update/', { isLocked: true }, alice); - await api('/following/create', { userId: alice.id }, bob); - await api('/following/create', { userId: alice.id }, carol); + await api('i/update', { isLocked: true }, alice); + await api('following/create', { userId: alice.id }, bob); + await api('following/create', { userId: alice.id }, carol); - const res = await api('/i/notifications-grouped', {}, alice); + const res = await api('i/notifications-grouped', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); diff --git a/packages/backend/test/e2e/note.ts b/packages/backend/test/e2e/note.ts index 2406204f41..bda31d9640 100644 --- a/packages/backend/test/e2e/note.ts +++ b/packages/backend/test/e2e/note.ts @@ -8,12 +8,13 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; import { MiNote } from '@/models/Note.js'; import { MAX_NOTE_TEXT_LENGTH } from '@/const.js'; -import { api, initTestDb, post, signup, uploadFile, uploadUrl } from '../utils.js'; +import { api, initTestDb, post, role, signup, uploadFile, uploadUrl } from '../utils.js'; import type * as misskey from 'misskey-js'; describe('Note', () => { let Notes: any; + let root: misskey.entities.SignupResponse; let alice: misskey.entities.SignupResponse; let bob: misskey.entities.SignupResponse; let tom: misskey.entities.SignupResponse; @@ -21,6 +22,7 @@ describe('Note', () => { beforeAll(async () => { const connection = await initTestDb(true); Notes = connection.getRepository(MiNote); + root = await signup({ username: 'root' }); alice = await signup({ username: 'alice' }); bob = await signup({ username: 'bob' }); tom = await signup({ username: 'tom', host: 'example.com' }); @@ -31,7 +33,7 @@ describe('Note', () => { text: 'test', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -41,7 +43,7 @@ describe('Note', () => { test('ファイルを添付できる', async () => { const file = await uploadUrl(alice, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg'); - const res = await api('/notes/create', { + const res = await api('notes/create', { fileIds: [file.id], }, alice); @@ -53,7 +55,7 @@ describe('Note', () => { test('他人のファイルで怒られる', async () => { const file = await uploadUrl(bob, 'https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg'); - const res = await api('/notes/create', { + const res = await api('notes/create', { text: 'test', fileIds: [file.id], }, alice); @@ -64,7 +66,7 @@ describe('Note', () => { }, 1000 * 10); test('存在しないファイルで怒られる', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { text: 'test', fileIds: ['000000000000000000000000'], }, alice); @@ -75,7 +77,7 @@ describe('Note', () => { }); test('不正なファイルIDで怒られる', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { fileIds: ['kyoppie'], }, alice); assert.strictEqual(res.status, 400); @@ -93,7 +95,7 @@ describe('Note', () => { replyId: bobPost.id, }; - const res = await api('/notes/create', alicePost, alice); + const res = await api('notes/create', alicePost, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -111,7 +113,7 @@ describe('Note', () => { renoteId: bobPost.id, }; - const res = await api('/notes/create', alicePost, alice); + const res = await api('notes/create', alicePost, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -129,7 +131,7 @@ describe('Note', () => { renoteId: bobPost.id, }; - const res = await api('/notes/create', alicePost, alice); + const res = await api('notes/create', alicePost, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -142,7 +144,7 @@ describe('Note', () => { const bobPost = await post(bob, { text: 'test', }); - const res = await api('/notes/create', { + const res = await api('notes/create', { text: ' ', renoteId: bobPost.id, }, alice); @@ -152,7 +154,7 @@ describe('Note', () => { }); test('visibility: followersでrenoteできる', async () => { - const createRes = await api('/notes/create', { + const createRes = await api('notes/create', { text: 'test', visibility: 'followers', }, alice); @@ -160,7 +162,7 @@ describe('Note', () => { assert.strictEqual(createRes.status, 200); const renoteId = createRes.body.createdNote.id; - const renoteRes = await api('/notes/create', { + const renoteRes = await api('notes/create', { visibility: 'followers', renoteId, }, alice); @@ -169,7 +171,7 @@ describe('Note', () => { assert.strictEqual(renoteRes.body.createdNote.renoteId, renoteId); assert.strictEqual(renoteRes.body.createdNote.visibility, 'followers'); - const deleteRes = await api('/notes/delete', { + const deleteRes = await api('notes/delete', { noteId: renoteRes.body.createdNote.id, }, alice); @@ -177,11 +179,11 @@ describe('Note', () => { }); test('visibility: followersなノートに対してフォロワーはリプライできる', async () => { - await api('/following/create', { + await api('following/create', { userId: alice.id, }, bob); - const aliceNote = await api('/notes/create', { + const aliceNote = await api('notes/create', { text: 'direct note to bob', visibility: 'followers', }, alice); @@ -189,7 +191,7 @@ describe('Note', () => { assert.strictEqual(aliceNote.status, 200); const replyId = aliceNote.body.createdNote.id; - const bobReply = await api('/notes/create', { + const bobReply = await api('notes/create', { text: 'reply to alice note', replyId, }, bob); @@ -197,20 +199,20 @@ describe('Note', () => { assert.strictEqual(bobReply.status, 200); assert.strictEqual(bobReply.body.createdNote.replyId, replyId); - await api('/following/delete', { + await api('following/delete', { userId: alice.id, }, bob); }); test('visibility: followersなノートに対してフォロワーでないユーザーがリプライしようとすると怒られる', async () => { - const aliceNote = await api('/notes/create', { + const aliceNote = await api('notes/create', { text: 'direct note to bob', visibility: 'followers', }, alice); assert.strictEqual(aliceNote.status, 200); - const bobReply = await api('/notes/create', { + const bobReply = await api('notes/create', { text: 'reply to alice note', replyId: aliceNote.body.createdNote.id, }, bob); @@ -220,7 +222,7 @@ describe('Note', () => { }); test('visibility: specifiedなノートに対してvisibility: specifiedで返信できる', async () => { - const aliceNote = await api('/notes/create', { + const aliceNote = await api('notes/create', { text: 'direct note to bob', visibility: 'specified', visibleUserIds: [bob.id], @@ -228,7 +230,7 @@ describe('Note', () => { assert.strictEqual(aliceNote.status, 200); - const bobReply = await api('/notes/create', { + const bobReply = await api('notes/create', { text: 'reply to alice note', replyId: aliceNote.body.createdNote.id, visibility: 'specified', @@ -239,7 +241,7 @@ describe('Note', () => { }); test('visibility: specifiedなノートに対してvisibility: follwersで返信しようとすると怒られる', async () => { - const aliceNote = await api('/notes/create', { + const aliceNote = await api('notes/create', { text: 'direct note to bob', visibility: 'specified', visibleUserIds: [bob.id], @@ -247,7 +249,7 @@ describe('Note', () => { assert.strictEqual(aliceNote.status, 200); - const bobReply = await api('/notes/create', { + const bobReply = await api('notes/create', { text: 'reply to alice note with visibility: followers', replyId: aliceNote.body.createdNote.id, visibility: 'followers', @@ -261,7 +263,7 @@ describe('Note', () => { const post = { text: '!'.repeat(MAX_NOTE_TEXT_LENGTH), // 3000文字 }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 200); }); @@ -269,7 +271,7 @@ describe('Note', () => { const post = { text: '!'.repeat(MAX_NOTE_TEXT_LENGTH + 1), // 3001文字 }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 400); }); @@ -278,7 +280,7 @@ describe('Note', () => { text: 'test', replyId: '000000000000000000000000', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 400); }); @@ -286,7 +288,7 @@ describe('Note', () => { const post = { renoteId: '000000000000000000000000', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 400); }); @@ -295,7 +297,7 @@ describe('Note', () => { text: 'test', replyId: 'foo', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 400); }); @@ -303,7 +305,7 @@ describe('Note', () => { const post = { renoteId: 'foo', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 400); }); @@ -312,7 +314,7 @@ describe('Note', () => { text: '@ghost yo', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -324,7 +326,7 @@ describe('Note', () => { text: '@bob @bob @bob yo', }; - const res = await api('/notes/create', post, alice); + const res = await api('notes/create', post, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); @@ -337,25 +339,25 @@ describe('Note', () => { describe('添付ファイル情報', () => { test('ファイルを添付した場合、投稿成功時にファイル情報入りのレスポンスが帰ってくる', async () => { const file = await uploadFile(alice); - const res = await api('/notes/create', { - fileIds: [file.body.id], + const res = await api('notes/create', { + fileIds: [file.body!.id], }, alice); assert.strictEqual(res.status, 200); assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); assert.strictEqual(res.body.createdNote.files.length, 1); - assert.strictEqual(res.body.createdNote.files[0].id, file.body.id); + assert.strictEqual(res.body.createdNote.files[0].id, file.body!.id); }); test('ファイルを添付した場合、タイムラインでファイル情報入りのレスポンスが帰ってくる', async () => { const file = await uploadFile(alice); - const createdNote = await api('/notes/create', { - fileIds: [file.body.id], + const createdNote = await api('notes/create', { + fileIds: [file.body!.id], }, alice); assert.strictEqual(createdNote.status, 200); - const res = await api('/notes', { + const res = await api('notes', { withFiles: true, }, alice); @@ -364,23 +366,23 @@ describe('Note', () => { const myNote = res.body.find((note: { id: string; files: { id: string }[] }) => note.id === createdNote.body.createdNote.id); assert.notEqual(myNote, null); assert.strictEqual(myNote.files.length, 1); - assert.strictEqual(myNote.files[0].id, file.body.id); + assert.strictEqual(myNote.files[0].id, file.body!.id); }); test('ファイルが添付されたノートをリノートした場合、タイムラインでファイル情報入りのレスポンスが帰ってくる', async () => { const file = await uploadFile(alice); - const createdNote = await api('/notes/create', { - fileIds: [file.body.id], + const createdNote = await api('notes/create', { + fileIds: [file.body!.id], }, alice); assert.strictEqual(createdNote.status, 200); - const renoted = await api('/notes/create', { + const renoted = await api('notes/create', { renoteId: createdNote.body.createdNote.id, }, alice); assert.strictEqual(renoted.status, 200); - const res = await api('/notes', { + const res = await api('notes', { renote: true, }, alice); @@ -389,24 +391,24 @@ describe('Note', () => { const myNote = res.body.find((note: { id: string }) => note.id === renoted.body.createdNote.id); assert.notEqual(myNote, null); assert.strictEqual(myNote.renote.files.length, 1); - assert.strictEqual(myNote.renote.files[0].id, file.body.id); + assert.strictEqual(myNote.renote.files[0].id, file.body!.id); }); test('ファイルが添付されたノートに返信した場合、タイムラインでファイル情報入りのレスポンスが帰ってくる', async () => { const file = await uploadFile(alice); - const createdNote = await api('/notes/create', { - fileIds: [file.body.id], + const createdNote = await api('notes/create', { + fileIds: [file.body!.id], }, alice); assert.strictEqual(createdNote.status, 200); - const reply = await api('/notes/create', { + const reply = await api('notes/create', { replyId: createdNote.body.createdNote.id, text: 'this is reply', }, alice); assert.strictEqual(reply.status, 200); - const res = await api('/notes', { + const res = await api('notes', { reply: true, }, alice); @@ -415,29 +417,29 @@ describe('Note', () => { const myNote = res.body.find((note: { id: string }) => note.id === reply.body.createdNote.id); assert.notEqual(myNote, null); assert.strictEqual(myNote.reply.files.length, 1); - assert.strictEqual(myNote.reply.files[0].id, file.body.id); + assert.strictEqual(myNote.reply.files[0].id, file.body!.id); }); test('ファイルが添付されたノートへの返信をリノートした場合、タイムラインでファイル情報入りのレスポンスが帰ってくる', async () => { const file = await uploadFile(alice); - const createdNote = await api('/notes/create', { - fileIds: [file.body.id], + const createdNote = await api('notes/create', { + fileIds: [file.body!.id], }, alice); assert.strictEqual(createdNote.status, 200); - const reply = await api('/notes/create', { + const reply = await api('notes/create', { replyId: createdNote.body.createdNote.id, text: 'this is reply', }, alice); assert.strictEqual(reply.status, 200); - const renoted = await api('/notes/create', { + const renoted = await api('notes/create', { renoteId: reply.body.createdNote.id, }, alice); assert.strictEqual(renoted.status, 200); - const res = await api('/notes', { + const res = await api('notes', { renote: true, }, alice); @@ -446,7 +448,7 @@ describe('Note', () => { const myNote = res.body.find((note: { id: string }) => note.id === renoted.body.createdNote.id); assert.notEqual(myNote, null); assert.strictEqual(myNote.renote.reply.files.length, 1); - assert.strictEqual(myNote.renote.reply.files[0].id, file.body.id); + assert.strictEqual(myNote.renote.reply.files[0].id, file.body!.id); }); test('NSFWが強制されている場合変更できない', async () => { @@ -472,26 +474,26 @@ describe('Note', () => { priority: 0, value: true, }, - }, - }, alice); + } as any, + }, root); assert.strictEqual(res.status, 200); const assign = await api('admin/roles/assign', { userId: alice.id, roleId: res.body.id, - }, alice); + }, root); assert.strictEqual(assign.status, 204); - assert.strictEqual(file.body.isSensitive, false); + assert.strictEqual(file.body!.isSensitive, false); const nsfwfile = await uploadFile(alice); assert.strictEqual(nsfwfile.status, 200); - assert.strictEqual(nsfwfile.body.isSensitive, true); + assert.strictEqual(nsfwfile.body!.isSensitive, true); const liftnsfw = await api('drive/files/update', { - fileId: nsfwfile.body.id, + fileId: nsfwfile.body!.id, isSensitive: false, }, alice); @@ -499,7 +501,7 @@ describe('Note', () => { assert.strictEqual(liftnsfw.body.error.code, 'RESTRICTED_BY_ROLE'); const oldaddnsfw = await api('drive/files/update', { - fileId: file.body.id, + fileId: file.body!.id, isSensitive: true, }, alice); @@ -508,17 +510,17 @@ describe('Note', () => { await api('admin/roles/unassign', { userId: alice.id, roleId: res.body.id, - }); + }, root); await api('admin/roles/delete', { roleId: res.body.id, - }, alice); + }, root); }); }); describe('notes/create', () => { test('投票を添付できる', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { text: 'test', poll: { choices: ['foo', 'bar'], @@ -531,14 +533,15 @@ describe('Note', () => { }); test('投票の選択肢が無くて怒られる', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { + // @ts-expect-error poll must not be empty poll: {}, }, alice); assert.strictEqual(res.status, 400); }); test('投票の選択肢が無くて怒られる (空の配列)', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { poll: { choices: [], }, @@ -547,7 +550,7 @@ describe('Note', () => { }); test('投票の選択肢が1つで怒られる', async () => { - const res = await api('/notes/create', { + const res = await api('notes/create', { poll: { choices: ['Strawberry Pasta'], }, @@ -556,14 +559,14 @@ describe('Note', () => { }); test('投票できる', async () => { - const { body } = await api('/notes/create', { + const { body } = await api('notes/create', { text: 'test', poll: { choices: ['sakura', 'izumi', 'ako'], }, }, alice); - const res = await api('/notes/polls/vote', { + const res = await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 1, }, alice); @@ -572,19 +575,19 @@ describe('Note', () => { }); test('複数投票できない', async () => { - const { body } = await api('/notes/create', { + const { body } = await api('notes/create', { text: 'test', poll: { choices: ['sakura', 'izumi', 'ako'], }, }, alice); - await api('/notes/polls/vote', { + await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 0, }, alice); - const res = await api('/notes/polls/vote', { + const res = await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 2, }, alice); @@ -593,7 +596,7 @@ describe('Note', () => { }); test('許可されている場合は複数投票できる', async () => { - const { body } = await api('/notes/create', { + const { body } = await api('notes/create', { text: 'test', poll: { choices: ['sakura', 'izumi', 'ako'], @@ -601,17 +604,17 @@ describe('Note', () => { }, }, alice); - await api('/notes/polls/vote', { + await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 0, }, alice); - await api('/notes/polls/vote', { + await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 1, }, alice); - const res = await api('/notes/polls/vote', { + const res = await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 2, }, alice); @@ -620,7 +623,7 @@ describe('Note', () => { }); test('締め切られている場合は投票できない', async () => { - const { body } = await api('/notes/create', { + const { body } = await api('notes/create', { text: 'test', poll: { choices: ['sakura', 'izumi', 'ako'], @@ -630,7 +633,7 @@ describe('Note', () => { await new Promise(x => setTimeout(x, 2)); - const res = await api('/notes/polls/vote', { + const res = await api('notes/polls/vote', { noteId: body.createdNote.id, choice: 1, }, alice); @@ -643,13 +646,13 @@ describe('Note', () => { sensitiveWords: [ 'test', ], - }, alice); + }, root); assert.strictEqual(sensitive.status, 204); await new Promise(x => setTimeout(x, 2)); - const note1 = await api('/notes/create', { + const note1 = await api('notes/create', { text: 'hogetesthuge', }, alice); @@ -662,11 +665,11 @@ describe('Note', () => { sensitiveWords: [ '/Test/i', ], - }, alice); + }, root); assert.strictEqual(sensitive.status, 204); - const note2 = await api('/notes/create', { + const note2 = await api('notes/create', { text: 'hogetesthuge', }, alice); @@ -679,11 +682,11 @@ describe('Note', () => { sensitiveWords: [ 'Test hoge', ], - }, alice); + }, root); assert.strictEqual(sensitive.status, 204); - const note2 = await api('/notes/create', { + const note2 = await api('notes/create', { text: 'hogeTesthuge', }, alice); @@ -696,13 +699,13 @@ describe('Note', () => { prohibitedWords: [ 'test', ], - }, alice); + }, root); assert.strictEqual(prohibited.status, 204); await new Promise(x => setTimeout(x, 2)); - const note1 = await api('/notes/create', { + const note1 = await api('notes/create', { text: 'hogetesthuge', }, alice); @@ -715,11 +718,11 @@ describe('Note', () => { prohibitedWords: [ '/Test/i', ], - }, alice); + }, root); assert.strictEqual(prohibited.status, 204); - const note2 = await api('/notes/create', { + const note2 = await api('notes/create', { text: 'hogetesthuge', }, alice); @@ -732,11 +735,11 @@ describe('Note', () => { prohibitedWords: [ 'Test hoge', ], - }, alice); + }, root); assert.strictEqual(prohibited.status, 204); - const note2 = await api('/notes/create', { + const note2 = await api('notes/create', { text: 'hogeTesthuge', }, alice); @@ -749,13 +752,13 @@ describe('Note', () => { prohibitedWords: [ 'test', ], - }, alice); + }, root); assert.strictEqual(prohibited.status, 204); await new Promise(x => setTimeout(x, 2)); - const note1 = await api('/notes/create', { + const note1 = await api('notes/create', { text: 'hogetesthuge', }, tom); @@ -783,8 +786,8 @@ describe('Note', () => { priority: 1, value: 0, }, - }, - }, alice); + } as any, + }, root); assert.strictEqual(res.status, 200); @@ -793,13 +796,13 @@ describe('Note', () => { const assign = await api('admin/roles/assign', { userId: alice.id, roleId: res.body.id, - }, alice); + }, root); assert.strictEqual(assign.status, 204); await new Promise(x => setTimeout(x, 2)); - const note = await api('/notes/create', { + const note = await api('notes/create', { text: '@bob potentially annoying text', }, alice); @@ -809,11 +812,11 @@ describe('Note', () => { await api('admin/roles/unassign', { userId: alice.id, roleId: res.body.id, - }); + }, root); await api('admin/roles/delete', { roleId: res.body.id, - }, alice); + }, root); }); test('ダイレクト投稿もエラーになる', async () => { @@ -837,8 +840,8 @@ describe('Note', () => { priority: 1, value: 0, }, - }, - }, alice); + } as any, + }, root); assert.strictEqual(res.status, 200); @@ -847,16 +850,16 @@ describe('Note', () => { const assign = await api('admin/roles/assign', { userId: alice.id, roleId: res.body.id, - }, alice); + }, root); assert.strictEqual(assign.status, 204); await new Promise(x => setTimeout(x, 2)); - const note = await api('/notes/create', { + const note = await api('notes/create', { text: 'potentially annoying text', visibility: 'specified', - visibleUserIds: [ bob.id ], + visibleUserIds: [bob.id], }, alice); assert.strictEqual(note.status, 400); @@ -865,11 +868,11 @@ describe('Note', () => { await api('admin/roles/unassign', { userId: alice.id, roleId: res.body.id, - }); + }, root); await api('admin/roles/delete', { roleId: res.body.id, - }, alice); + }, root); }); test('ダイレクトの宛先とメンションが同じ場合は重複してカウントしない', async () => { @@ -893,8 +896,8 @@ describe('Note', () => { priority: 1, value: 1, }, - }, - }, alice); + } as any, + }, root); assert.strictEqual(res.status, 200); @@ -903,16 +906,16 @@ describe('Note', () => { const assign = await api('admin/roles/assign', { userId: alice.id, roleId: res.body.id, - }, alice); + }, root); assert.strictEqual(assign.status, 204); await new Promise(x => setTimeout(x, 2)); - const note = await api('/notes/create', { + const note = await api('notes/create', { text: '@bob potentially annoying text', visibility: 'specified', - visibleUserIds: [ bob.id ], + visibleUserIds: [bob.id], }, alice); assert.strictEqual(note.status, 200); @@ -920,11 +923,11 @@ describe('Note', () => { await api('admin/roles/unassign', { userId: alice.id, roleId: res.body.id, - }); + }, root); await api('admin/roles/delete', { roleId: res.body.id, - }, alice); + }, root); }); }); @@ -959,4 +962,61 @@ describe('Note', () => { assert.strictEqual(mainNote.repliesCount, 0); }); }); + + describe('notes/translate', () => { + describe('翻訳機能の利用が許可されていない場合', () => { + let cannotTranslateRole: misskey.entities.Role; + + beforeAll(async () => { + cannotTranslateRole = await role(root, {}, { canUseTranslator: false }); + await api('admin/roles/assign', { roleId: cannotTranslateRole.id, userId: alice.id }, root); + }); + + test('翻訳機能の利用が許可されていない場合翻訳できない', async () => { + const aliceNote = await post(alice, { text: 'Hello' }); + const res = await api('notes/translate', { + noteId: aliceNote.id, + targetLang: 'ja', + }, alice); + + assert.strictEqual(res.status, 400); + assert.strictEqual(res.body.error.code, 'UNAVAILABLE'); + }); + + afterAll(async () => { + await api('admin/roles/unassign', { roleId: cannotTranslateRole.id, userId: alice.id }, root); + }); + }); + + test('存在しないノートは翻訳できない', async () => { + const res = await api('notes/translate', { noteId: 'foo', targetLang: 'ja' }, alice); + + assert.strictEqual(res.status, 400); + assert.strictEqual(res.body.error.code, 'NO_SUCH_NOTE'); + }); + + test('不可視なノートは翻訳できない', async () => { + const aliceNote = await post(alice, { visibility: 'followers', text: 'Hello' }); + const bobTranslateAttempt = await api('notes/translate', { noteId: aliceNote.id, targetLang: 'ja' }, bob); + + assert.strictEqual(bobTranslateAttempt.status, 400); + assert.strictEqual(bobTranslateAttempt.body.error.code, 'CANNOT_TRANSLATE_INVISIBLE_NOTE'); + }); + + test('text: null なノートを翻訳すると空のレスポンスが返ってくる', async () => { + const aliceNote = await post(alice, { text: null, poll: { choices: ['kinoko', 'takenoko'] } }); + const res = await api('notes/translate', { noteId: aliceNote.id, targetLang: 'ja' }, alice); + + assert.strictEqual(res.status, 204); + }); + + test('サーバーに DeepL 認証キーが登録されていない場合翻訳できない', async () => { + const aliceNote = await post(alice, { text: 'Hello' }); + const res = await api('notes/translate', { noteId: aliceNote.id, targetLang: 'ja' }, alice); + + // NOTE: デフォルトでは登録されていないので落ちる + assert.strictEqual(res.status, 400); + assert.strictEqual(res.body.error.code, 'UNAVAILABLE'); + }); + }); }); diff --git a/packages/backend/test/e2e/renote-mute.ts b/packages/backend/test/e2e/renote-mute.ts index 403de0cb8d..1abbb4f044 100644 --- a/packages/backend/test/e2e/renote-mute.ts +++ b/packages/backend/test/e2e/renote-mute.ts @@ -22,7 +22,7 @@ describe('Renote Mute', () => { }, 1000 * 60 * 2); test('ミュート作成', async () => { - const res = await api('/renote-mute/create', { + const res = await api('renote-mute/create', { userId: carol.id, }, alice); @@ -37,7 +37,7 @@ describe('Renote Mute', () => { // redisに追加されるのを待つ await sleep(100); - const res = await api('/notes/local-timeline', {}, alice); + const res = await api('notes/local-timeline', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -54,7 +54,7 @@ describe('Renote Mute', () => { // redisに追加されるのを待つ await sleep(100); - const res = await api('/notes/local-timeline', {}, alice); + const res = await api('notes/local-timeline', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -63,6 +63,22 @@ describe('Renote Mute', () => { assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); }); + // #12956 + test('タイムラインにリノートミュートしているユーザーの通常ノートのリノートが含まれる', async () => { + const carolNote = await post(carol, { text: 'hi' }); + const bobRenote = await post(bob, { renoteId: carolNote.id }); + + // redisに追加されるのを待つ + await sleep(100); + + const res = await api('notes/local-timeline', {}, alice); + + assert.strictEqual(res.status, 200); + assert.strictEqual(Array.isArray(res.body), true); + assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); + assert.strictEqual(res.body.some((note: any) => note.id === bobRenote.id), true); + }); + test('ストリームにリノートミュートしているユーザーのリノートが流れない', async () => { const bobNote = await post(bob, { text: 'hi' }); @@ -86,4 +102,17 @@ describe('Renote Mute', () => { assert.strictEqual(fired, true); }); + + // #12956 + test('ストリームにリノートミュートしているユーザーの通常ノートのリノートが流れてくる', async () => { + const carolbNote = await post(carol, { text: 'hi' }); + + const fired = await waitFire( + alice, 'localTimeline', + () => api('notes/create', { renoteId: carolbNote.id }, bob), + msg => msg.type === 'note' && msg.body.userId === bob.id, + ); + + assert.strictEqual(fired, true); + }); }); diff --git a/packages/backend/test/e2e/streaming.ts b/packages/backend/test/e2e/streaming.ts index 57ce73ba60..b0a70074c6 100644 --- a/packages/backend/test/e2e/streaming.ts +++ b/packages/backend/test/e2e/streaming.ts @@ -63,7 +63,7 @@ describe('Streaming', () => { takumiNote = await post(takumi, { text: 'piyo' }); // Follow: ayano => kyoko - await api('following/create', { userId: kyoko.id }, ayano); + await api('following/create', { userId: kyoko.id, withReplies: false }, ayano); // Follow: ayano => akari await follow(ayano, akari); @@ -158,19 +158,17 @@ describe('Streaming', () => { assert.strictEqual(fired, true); }); - /* なんか失敗する test('フォローしているユーザーの visibility: followers な投稿への返信が流れる', async () => { - const note = await api('notes/create', { text: 'foo', visibility: 'followers' }, kyoko); + const note = await post(kyoko, { text: 'foo', visibility: 'followers' }); const fired = await waitFire( ayano, 'homeTimeline', // ayano:home - () => api('notes/create', { text: 'bar', visibility: 'followers', replyId: note.body.id }, kyoko), // kyoko posts + () => api('notes/create', { text: 'bar', visibility: 'followers', replyId: note.id }, kyoko), // kyoko posts msg => msg.type === 'note' && msg.body.userId === kyoko.id && msg.body.reply.text === 'foo', ); assert.strictEqual(fired, true); }); - */ test('フォローしているユーザーのフォローしていないユーザーの visibility: followers な投稿への返信が流れない', async () => { const chitoseNote = await post(chitose, { text: 'followers-only post', visibility: 'followers' }); @@ -511,6 +509,16 @@ describe('Streaming', () => { assert.strictEqual(fired, false); }); + + test('withReplies = falseでフォローしてる人によるリプライが流れてくる', async () => { + const fired = await waitFire( + ayano, 'globalTimeline', // ayano:Global + () => api('notes/create', { text: 'foo', replyId: kanakoNote.id }, kyoko), // kyoko posts + msg => msg.type === 'note' && msg.body.userId === kyoko.id, // wait kyoko + ); + + assert.strictEqual(fired, true); + }); }); describe('UserList Timeline', () => { @@ -601,7 +609,7 @@ describe('Streaming', () => { // #10443 test('ミュートしているサーバのノートがリストTLに流れない', async () => { - await api('/i/update', { + await api('i/update', { mutedInstances: ['example.com'], }, chitose); @@ -618,7 +626,7 @@ describe('Streaming', () => { // #10443 test('ミュートしているサーバのノートに対するリプライがリストTLに流れない', async () => { - await api('/i/update', { + await api('i/update', { mutedInstances: ['example.com'], }, chitose); @@ -635,7 +643,7 @@ describe('Streaming', () => { // #10443 test('ミュートしているサーバのノートに対するリノートがリストTLに流れない', async () => { - await api('/i/update', { + await api('i/update', { mutedInstances: ['example.com'], }, chitose); diff --git a/packages/backend/test/e2e/thread-mute.ts b/packages/backend/test/e2e/thread-mute.ts index b4570cdef1..53bb6eb765 100644 --- a/packages/backend/test/e2e/thread-mute.ts +++ b/packages/backend/test/e2e/thread-mute.ts @@ -24,12 +24,12 @@ describe('Note thread mute', () => { const bobNote = await post(bob, { text: '@alice @carol root note' }); const aliceReply = await post(alice, { replyId: bobNote.id, text: '@bob @carol child note' }); - await api('/notes/thread-muting/create', { noteId: bobNote.id }, alice); + await api('notes/thread-muting/create', { noteId: bobNote.id }, alice); const carolReply = await post(carol, { replyId: bobNote.id, text: '@bob @alice child note' }); const carolReplyWithoutMention = await post(carol, { replyId: aliceReply.id, text: 'child note' }); - const res = await api('/notes/mentions', {}, alice); + const res = await api('notes/mentions', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); @@ -40,15 +40,15 @@ describe('Note thread mute', () => { test('ミュートしているスレッドからメンションされても、hasUnreadMentions が true にならない', async () => { // 状態リセット - await api('/i/read-all-unread-notes', {}, alice); + await api('i/read-all-unread-notes', {}, alice); const bobNote = await post(bob, { text: '@alice @carol root note' }); - await api('/notes/thread-muting/create', { noteId: bobNote.id }, alice); + await api('notes/thread-muting/create', { noteId: bobNote.id }, alice); const carolReply = await post(carol, { replyId: bobNote.id, text: '@bob @alice child note' }); - const res = await api('/i', {}, alice); + const res = await api('i', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(res.body.hasUnreadMentions, false); @@ -56,11 +56,11 @@ describe('Note thread mute', () => { test('ミュートしているスレッドからメンションされても、ストリームに unreadMention イベントが流れてこない', () => new Promise(async done => { // 状態リセット - await api('/i/read-all-unread-notes', {}, alice); + await api('i/read-all-unread-notes', {}, alice); const bobNote = await post(bob, { text: '@alice @carol root note' }); - await api('/notes/thread-muting/create', { noteId: bobNote.id }, alice); + await api('notes/thread-muting/create', { noteId: bobNote.id }, alice); let fired = false; @@ -84,12 +84,12 @@ describe('Note thread mute', () => { const bobNote = await post(bob, { text: '@alice @carol root note' }); const aliceReply = await post(alice, { replyId: bobNote.id, text: '@bob @carol child note' }); - await api('/notes/thread-muting/create', { noteId: bobNote.id }, alice); + await api('notes/thread-muting/create', { noteId: bobNote.id }, alice); const carolReply = await post(carol, { replyId: bobNote.id, text: '@bob @alice child note' }); const carolReplyWithoutMention = await post(carol, { replyId: aliceReply.id, text: 'child note' }); - const res = await api('/i/notifications', {}, alice); + const res = await api('i/notifications', {}, alice); assert.strictEqual(res.status, 200); assert.strictEqual(Array.isArray(res.body), true); diff --git a/packages/backend/test/e2e/timelines.ts b/packages/backend/test/e2e/timelines.ts index 0e71d707dd..5487292afc 100644 --- a/packages/backend/test/e2e/timelines.ts +++ b/packages/backend/test/e2e/timelines.ts @@ -26,7 +26,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === aliceNote.id).text, 'hi'); @@ -35,14 +35,14 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーのノートが含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi' }); const carolNote = await post(carol, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -51,14 +51,14 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの visibility: followers なノートが含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'followers' }); const carolNote = await post(carol, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'hi'); @@ -68,14 +68,14 @@ describe('Timelines', () => { test.concurrent('withReplies: false でフォローしているユーザーの他人への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -84,15 +84,15 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーの他人への返信が含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -101,15 +101,15 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーの他人へのDM返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id, visibility: 'specified', visibleUserIds: [carolNote.id] }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -118,15 +118,15 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーの他人の visibility: followers な投稿への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi', visibility: 'followers' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -135,17 +135,17 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーの行った別のフォローしているユーザーの visibility: followers な投稿への返信が含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/create', { userId: carol.id }, alice); - await api('/following/create', { userId: carol.id }, bob); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/create', { userId: carol.id }, alice); + await api('following/create', { userId: carol.id }, bob); + await api('following/update', { userId: bob.id, withReplies: true }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi', visibility: 'followers' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); @@ -155,16 +155,16 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーの行った別のフォローしているユーザーの投稿への visibility: specified な返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/create', { userId: carol.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/create', { userId: carol.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id, visibility: 'specified', visibleUserIds: [carolNote.id] }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); @@ -173,14 +173,14 @@ describe('Timelines', () => { test.concurrent('withReplies: false でフォローしているユーザーのそのユーザー自身への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote1 = await post(bob, { text: 'hi' }); const bobNote2 = await post(bob, { text: 'hi', replyId: bobNote1.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -189,14 +189,14 @@ describe('Timelines', () => { test.concurrent('withReplies: false でフォローしているユーザーからの自分への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const aliceNote = await post(alice, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); @@ -210,7 +210,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); @@ -219,14 +219,14 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの他人の投稿のリノートが含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -235,14 +235,14 @@ describe('Timelines', () => { test.concurrent('[withRenotes: false] フォローしているユーザーの他人の投稿のリノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { + const res = await api('notes/timeline', { withRenotes: false, }, alice); @@ -253,14 +253,14 @@ describe('Timelines', () => { test.concurrent('[withRenotes: false] フォローしているユーザーの他人の投稿の引用が含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { + const res = await api('notes/timeline', { withRenotes: false, }, alice); @@ -271,13 +271,13 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの他人への visibility: specified なノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'specified', visibleUserIds: [carol.id] }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -285,15 +285,15 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーが行ったミュートしているユーザーのリノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/mute/create', { userId: carol.id }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -302,16 +302,16 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーが行ったミュートしているユーザーの投稿への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); - await api('/mute/create', { userId: carol.id }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -321,13 +321,13 @@ describe('Timelines', () => { const [alice, bob] = await Promise.all([signup(), signup({ host: genHost() })]); await sendEnvUpdateRequest({ key: 'FORCE_FOLLOW_REMOTE_USER_FOR_TESTING', value: 'true' }); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); const bobNote = await post(bob, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -336,13 +336,13 @@ describe('Timelines', () => { const [alice, bob] = await Promise.all([signup(), signup({ host: genHost() })]); await sendEnvUpdateRequest({ key: 'FORCE_FOLLOW_REMOTE_USER_FOR_TESTING', value: 'true' }); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); const bobNote = await post(bob, { text: 'hi', visibility: 'home' }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -350,7 +350,7 @@ describe('Timelines', () => { test.concurrent('[withFiles: true] フォローしているユーザーのファイル付きノートのみ含まれる', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const [bobFile, carolFile] = await Promise.all([ uploadUrl(bob, 'https://raw.githubusercontent.com/misskey-dev/assets/main/public/icon.png'), @@ -363,7 +363,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100, withFiles: true }, alice); + const res = await api('notes/timeline', { limit: 100, withFiles: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), false); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -374,14 +374,14 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーのチャンネル投稿が含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel' }, bob).then(x => x.body); - await api('/following/create', { userId: bob.id }, alice); + const channel = await api('channels/create', { name: 'channel' }, bob).then(x => x.body); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -393,7 +393,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === aliceNote.id).text, 'hi'); @@ -402,13 +402,13 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの自身を visibleUserIds に指定した visibility: specified なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'specified', visibleUserIds: [alice.id] }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'hi'); @@ -421,7 +421,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -429,13 +429,13 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの自身を visibleUserIds に指定していない visibility: specified なノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'specified', visibleUserIds: [carol.id] }); await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -448,7 +448,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === aliceNote.id).text, 'ok'); @@ -463,7 +463,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'ok'); @@ -479,7 +479,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/timeline', { limit: 100 }, alice); + const res = await api('notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -494,7 +494,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -508,7 +508,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); @@ -522,7 +522,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -531,12 +531,12 @@ describe('Timelines', () => { test.concurrent('チャンネル投稿が含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel' }, bob).then(x => x.body); + const channel = await api('channels/create', { name: 'channel' }, bob).then(x => x.body); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -548,7 +548,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -557,14 +557,14 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの visibility: home なノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: carol.id }, alice); + await api('following/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi', visibility: 'home' }); const bobNote = await post(bob, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -573,14 +573,14 @@ describe('Timelines', () => { test.concurrent('ミュートしているユーザーのノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/mute/create', { userId: carol.id }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -589,15 +589,15 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーが行ったミュートしているユーザーのリノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/mute/create', { userId: carol.id }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -606,16 +606,16 @@ describe('Timelines', () => { test.concurrent('withReplies: true でフォローしているユーザーが行ったミュートしているユーザーの投稿への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - await api('/following/update', { userId: bob.id, withReplies: true }, alice); - await api('/mute/create', { userId: carol.id }, alice); + await api('following/create', { userId: bob.id }, alice); + await api('following/update', { userId: bob.id, withReplies: true }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), false); @@ -624,14 +624,14 @@ describe('Timelines', () => { test.concurrent('withReplies: false でフォローしているユーザーからの自分への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const aliceNote = await post(alice, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id }); await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); @@ -645,7 +645,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100, withReplies: true }, alice); + const res = await api('notes/local-timeline', { limit: 100, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -659,7 +659,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100, withFiles: true }, alice); + const res = await api('notes/local-timeline', { limit: 100, withFiles: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), false); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -674,7 +674,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -686,7 +686,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -694,13 +694,13 @@ describe('Timelines', () => { test.concurrent('フォローしているローカルユーザーの visibility: home なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'home' }); await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -708,14 +708,14 @@ describe('Timelines', () => { test.concurrent('withReplies: false でフォローしているユーザーからの自分への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const aliceNote = await post(alice, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id }); await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); @@ -729,7 +729,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); assert.strictEqual(res.body.some((note: any) => note.id === carolNote.id), true); @@ -742,7 +742,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/local-timeline', { limit: 100 }, alice); + const res = await api('notes/local-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -751,13 +751,13 @@ describe('Timelines', () => { const [alice, bob] = await Promise.all([signup(), signup({ host: genHost() })]); await sendEnvUpdateRequest({ key: 'FORCE_FOLLOW_REMOTE_USER_FOR_TESTING', value: 'true' }); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); const bobNote = await post(bob, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -766,13 +766,13 @@ describe('Timelines', () => { const [alice, bob] = await Promise.all([signup(), signup({ host: genHost() })]); await sendEnvUpdateRequest({ key: 'FORCE_FOLLOW_REMOTE_USER_FOR_TESTING', value: 'true' }); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); const bobNote = await post(bob, { text: 'hi', visibility: 'home' }); await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100 }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100 }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -785,7 +785,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100, withReplies: true }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -799,7 +799,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/notes/hybrid-timeline', { limit: 100, withFiles: true }, alice); + const res = await api('notes/hybrid-timeline', { limit: 100, withFiles: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), false); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -810,14 +810,14 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしていないユーザーのノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -825,14 +825,14 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしていないユーザーの visibility: home なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'home' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -840,14 +840,14 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしていないユーザーの visibility: followers なノートが含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'followers' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -855,15 +855,15 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしていないユーザーの他人への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -871,15 +871,15 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしていないユーザーのユーザー自身への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote1 = await post(bob, { text: 'hi' }); const bobNote2 = await post(bob, { text: 'hi', replyId: bobNote1.id }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -888,32 +888,50 @@ describe('Timelines', () => { test.concurrent('withReplies: false でリスインしているフォローしていないユーザーからの自分への返信が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: false }, alice); await sleep(1000); const aliceNote = await post(alice, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id, withReplies: false }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); - test.concurrent('withReplies: true でリスインしているフォローしていないユーザーの他人への返信が含まれる', async () => { + test.concurrent('withReplies: false でリスインしているフォローしていないユーザーの他人への返信が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); - await api('/users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: true }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: false }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); + + assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); + }); + + test.concurrent('withReplies: true でリスインしているフォローしていないユーザーの他人への返信が含まれる', async () => { + const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); + + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: true }, alice); + await sleep(1000); + const carolNote = await post(carol, { text: 'hi' }); + const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id }); + + await waitForPushToTl(); + + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -921,15 +939,15 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしているユーザーの visibility: home なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'home' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -937,15 +955,15 @@ describe('Timelines', () => { test.concurrent('リスインしているフォローしているユーザーの visibility: followers なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'followers' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'hi'); @@ -954,14 +972,14 @@ describe('Timelines', () => { test.concurrent('リスインしている自分の visibility: followers なノートが含まれる', async () => { const [alice] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: alice.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: alice.id }, alice); await sleep(1000); const aliceNote = await post(alice, { text: 'hi', visibility: 'followers' }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === aliceNote.id).text, 'hi'); @@ -970,15 +988,15 @@ describe('Timelines', () => { test.concurrent('リスインしているユーザーのチャンネルノートが含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel' }, bob).then(x => x.body); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const channel = await api('channels/create', { name: 'channel' }, bob).then(x => x.body); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -986,15 +1004,15 @@ describe('Timelines', () => { test.concurrent('[withFiles: true] リスインしているユーザーのファイル付きノートのみ含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); const file = await uploadUrl(bob, 'https://raw.githubusercontent.com/misskey-dev/assets/main/public/icon.png'); const bobNote1 = await post(bob, { text: 'hi' }); const bobNote2 = await post(bob, { fileIds: [file.id] }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id, withFiles: true }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id, withFiles: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), false); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -1003,14 +1021,14 @@ describe('Timelines', () => { test.concurrent('リスインしているユーザーの自身宛ての visibility: specified なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'specified', visibleUserIds: [alice.id] }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'hi'); @@ -1019,15 +1037,15 @@ describe('Timelines', () => { test.concurrent('リスインしているユーザーの自身宛てではない visibility: specified なノートが含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - const list = await api('/users/lists/create', { name: 'list' }, alice).then(res => res.body); - await api('/users/lists/push', { listId: list.id, userId: bob.id }, alice); - await api('/users/lists/push', { listId: list.id, userId: carol.id }, alice); + const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); + await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); + await api('users/lists/push', { listId: list.id, userId: carol.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'specified', visibleUserIds: [carol.id] }); await waitForPushToTl(); - const res = await api('/notes/user-list-timeline', { listId: list.id }, alice); + const res = await api('notes/user-list-timeline', { listId: list.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -1041,7 +1059,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -1053,7 +1071,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -1061,13 +1079,13 @@ describe('Timelines', () => { test.concurrent('フォローしているユーザーの visibility: followers なノートが含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/following/create', { userId: bob.id }, alice); + await api('following/create', { userId: bob.id }, alice); await sleep(1000); const bobNote = await post(bob, { text: 'hi', visibility: 'followers' }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === bobNote.id).text, 'hi'); @@ -1080,7 +1098,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: alice.id }, alice); + const res = await api('users/notes', { userId: alice.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); assert.strictEqual(res.body.find((note: any) => note.id === aliceNote.id).text, 'hi'); @@ -1089,12 +1107,12 @@ describe('Timelines', () => { test.concurrent('チャンネル投稿が含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel' }, bob).then(x => x.body); + const channel = await api('channels/create', { name: 'channel' }, bob).then(x => x.body); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -1108,7 +1126,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), false); @@ -1123,7 +1141,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withReplies: true }, alice); + const res = await api('users/notes', { userId: bob.id, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -1138,7 +1156,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withReplies: true }, alice); + const res = await api('users/notes', { userId: bob.id, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), false); @@ -1153,7 +1171,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withFiles: true }, alice); + const res = await api('users/notes', { userId: bob.id, withFiles: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), false); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -1162,12 +1180,12 @@ describe('Timelines', () => { test.concurrent('[withChannelNotes: true] チャンネル投稿が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel' }, bob).then(x => x.body); + const channel = await api('channels/create', { name: 'channel' }, bob).then(x => x.body); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withChannelNotes: true }, alice); + const res = await api('users/notes', { userId: bob.id, withChannelNotes: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -1175,12 +1193,12 @@ describe('Timelines', () => { test.concurrent('[withChannelNotes: true] 他人が取得した場合センシティブチャンネル投稿が含まれない', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - const channel = await api('/channels/create', { name: 'channel', isSensitive: true }, bob).then(x => x.body); + const channel = await api('channels/create', { name: 'channel', isSensitive: true }, bob).then(x => x.body); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withChannelNotes: true }, alice); + const res = await api('users/notes', { userId: bob.id, withChannelNotes: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -1188,12 +1206,12 @@ describe('Timelines', () => { test.concurrent('[withChannelNotes: true] 自分が取得した場合センシティブチャンネル投稿が含まれる', async () => { const [bob] = await Promise.all([signup()]); - const channel = await api('/channels/create', { name: 'channel', isSensitive: true }, bob).then(x => x.body); + const channel = await api('channels/create', { name: 'channel', isSensitive: true }, bob).then(x => x.body); const bobNote = await post(bob, { text: 'hi', channelId: channel.id }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withChannelNotes: true }, bob); + const res = await api('users/notes', { userId: bob.id, withChannelNotes: true }, bob); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); }); @@ -1201,14 +1219,14 @@ describe('Timelines', () => { test.concurrent('ミュートしているユーザーに関連する投稿が含まれない', async () => { const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); - await api('/mute/create', { userId: carol.id }, alice); + await api('mute/create', { userId: carol.id }, alice); await sleep(1000); const carolNote = await post(carol, { text: 'hi' }); const bobNote = await post(bob, { text: 'hi', renoteId: carolNote.id }); await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); @@ -1216,7 +1234,7 @@ describe('Timelines', () => { test.concurrent('ミュートしていても userId に指定したユーザーの投稿が含まれる', async () => { const [alice, bob] = await Promise.all([signup(), signup()]); - await api('/mute/create', { userId: bob.id }, alice); + await api('mute/create', { userId: bob.id }, alice); await sleep(1000); const bobNote1 = await post(bob, { text: 'hi' }); const bobNote2 = await post(bob, { text: 'hi', replyId: bobNote1.id }); @@ -1224,7 +1242,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id }, alice); + const res = await api('users/notes', { userId: bob.id }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote1.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote2.id), true); @@ -1238,7 +1256,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: alice.id, withReplies: true }, alice); + const res = await api('users/notes', { userId: alice.id, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === aliceNote.id), true); }); @@ -1250,7 +1268,7 @@ describe('Timelines', () => { await waitForPushToTl(); - const res = await api('/users/notes', { userId: bob.id, withReplies: true }, alice); + const res = await api('users/notes', { userId: bob.id, withReplies: true }, alice); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false); }); diff --git a/packages/backend/test/e2e/user-notes.ts b/packages/backend/test/e2e/user-notes.ts index 6897cf08c6..331e053935 100644 --- a/packages/backend/test/e2e/user-notes.ts +++ b/packages/backend/test/e2e/user-notes.ts @@ -11,9 +11,9 @@ import type * as misskey from 'misskey-js'; describe('users/notes', () => { let alice: misskey.entities.SignupResponse; - let jpgNote: any; - let pngNote: any; - let jpgPngNote: any; + let jpgNote: misskey.entities.Note; + let pngNote: misskey.entities.Note; + let jpgPngNote: misskey.entities.Note; beforeAll(async () => { alice = await signup({ username: 'alice' }); @@ -31,7 +31,7 @@ describe('users/notes', () => { }, 1000 * 60 * 2); test('withFiles', async () => { - const res = await api('/users/notes', { + const res = await api('users/notes', { userId: alice.id, withFiles: true, }, alice); diff --git a/packages/backend/test/e2e/users.ts b/packages/backend/test/e2e/users.ts index 19b905dd47..89d48158ea 100644 --- a/packages/backend/test/e2e/users.ts +++ b/packages/backend/test/e2e/users.ts @@ -8,7 +8,7 @@ process.env.NODE_ENV = 'test'; import * as assert from 'assert'; import { inspect } from 'node:util'; import { DEFAULT_POLICIES } from '@/core/RoleService.js'; -import { api, page, post, role, signup, successfulApiCall, uploadFile } from '../utils.js'; +import { api, post, role, signup, successfulApiCall, uploadFile } from '../utils.js'; import type * as misskey from 'misskey-js'; describe('ユーザー', () => { @@ -24,31 +24,12 @@ describe('ユーザー', () => { }, {}); }; - // BUG misskey-jsとjson-schemaと実際に返ってくるデータが全部違う - type UserLite = misskey.entities.UserLite & { - badgeRoles: any[], - }; - - type UserDetailedNotMe = UserLite & - misskey.entities.UserDetailed & { - roles: any[], - }; - - type MeDetailed = UserDetailedNotMe & - misskey.entities.MeDetailed & { - achievements: object[], - loggedInDays: number, - policies: object, - }; - - type User = MeDetailed & { token: string }; - - const show = async (id: string, me = root): Promise => { - return successfulApiCall({ endpoint: 'users/show', parameters: { userId: id }, user: me }) as any; + const show = async (id: string, me = root): Promise => { + return successfulApiCall({ endpoint: 'users/show', parameters: { userId: id }, user: me }); }; // UserLiteのキーが過不足なく入っている? - const userLite = (user: User): Partial => { + const userLite = (user: misskey.entities.UserLite): Partial => { return stripUndefined({ id: user.id, name: user.name, @@ -72,7 +53,7 @@ describe('ユーザー', () => { }; // UserDetailedNotMeのキーが過不足なく入っている? - const userDetailedNotMe = (user: User): Partial => { + const userDetailedNotMe = (user: misskey.entities.SignupResponse): Partial => { return stripUndefined({ ...userLite(user), url: user.url, @@ -114,7 +95,7 @@ describe('ユーザー', () => { }; // Relations関連のキーが過不足なく入っている? - const userDetailedNotMeWithRelations = (user: User): Partial => { + const userDetailedNotMeWithRelations = (user: misskey.entities.SignupResponse): Partial => { return stripUndefined({ ...userDetailedNotMe(user), isFollowing: user.isFollowing ?? false, @@ -131,7 +112,7 @@ describe('ユーザー', () => { }; // MeDetailedのキーが過不足なく入っている? - const meDetailed = (user: User, security = false): Partial => { + const meDetailed = (user: misskey.entities.SignupResponse, security = false): Partial => { return stripUndefined({ ...userDetailedNotMe(user), avatarId: user.avatarId, @@ -162,6 +143,7 @@ describe('ユーザー', () => { mutedWords: user.mutedWords, hardMutedWords: user.hardMutedWords, mutedInstances: user.mutedInstances, + // @ts-expect-error 後方互換性 mutingNotificationTypes: user.mutingNotificationTypes, notificationRecieveConfig: user.notificationRecieveConfig, emailNotificationTypes: user.emailNotificationTypes, @@ -176,61 +158,53 @@ describe('ユーザー', () => { }); }; - let root: User; - let alice: User; + let root: misskey.entities.SignupResponse; + let alice: misskey.entities.SignupResponse; let aliceNote: misskey.entities.Note; - let alicePage: misskey.entities.Page; - let aliceList: misskey.entities.UserList; - let bob: User; - let bobNote: misskey.entities.Note; + let bob: misskey.entities.SignupResponse; - let carol: User; - let dave: User; - let ellen: User; - let frank: User; + // NOTE: これがないと落ちる(bob の updatedAt が null になってしまうため?) + let bobNote: misskey.entities.Note; // eslint-disable-line @typescript-eslint/no-unused-vars - let usersReplying: User[]; + let carol: misskey.entities.SignupResponse; - let userNoNote: User; - let userNotExplorable: User; - let userLocking: User; - let userAdmin: User; - let roleAdmin: any; - let userModerator: User; - let roleModerator: any; - let userRolePublic: User; - let rolePublic: any; - let userRoleBadge: User; - let roleBadge: any; - let userSilenced: User; - let roleSilenced: any; - let userSuspended: User; - let userDeletedBySelf: User; - let userDeletedByAdmin: User; - let userFollowingAlice: User; - let userFollowedByAlice: User; - let userBlockingAlice: User; - let userBlockedByAlice: User; - let userMutingAlice: User; - let userMutedByAlice: User; - let userRnMutingAlice: User; - let userRnMutedByAlice: User; - let userFollowRequesting: User; - let userFollowRequested: User; + let usersReplying: misskey.entities.SignupResponse[]; + + let userNoNote: misskey.entities.SignupResponse; + let userNotExplorable: misskey.entities.SignupResponse; + let userLocking: misskey.entities.SignupResponse; + let userAdmin: misskey.entities.SignupResponse; + let roleAdmin: misskey.entities.Role; + let userModerator: misskey.entities.SignupResponse; + let roleModerator: misskey.entities.Role; + let userRolePublic: misskey.entities.SignupResponse; + let rolePublic: misskey.entities.Role; + let userRoleBadge: misskey.entities.SignupResponse; + let roleBadge: misskey.entities.Role; + let userSilenced: misskey.entities.SignupResponse; + let roleSilenced: misskey.entities.Role; + let userSuspended: misskey.entities.SignupResponse; + let userDeletedBySelf: misskey.entities.SignupResponse; + let userDeletedByAdmin: misskey.entities.SignupResponse; + let userFollowingAlice: misskey.entities.SignupResponse; + let userFollowedByAlice: misskey.entities.SignupResponse; + let userBlockingAlice: misskey.entities.SignupResponse; + let userBlockedByAlice: misskey.entities.SignupResponse; + let userMutingAlice: misskey.entities.SignupResponse; + let userMutedByAlice: misskey.entities.SignupResponse; + let userRnMutingAlice: misskey.entities.SignupResponse; + let userRnMutedByAlice: misskey.entities.SignupResponse; + let userFollowRequesting: misskey.entities.SignupResponse; + let userFollowRequested: misskey.entities.SignupResponse; beforeAll(async () => { root = await signup({ username: 'root' }); alice = await signup({ username: 'alice' }); - aliceNote = await post(alice, { text: 'test' }) as any; - alicePage = await page(alice); - aliceList = (await api('users/list/create', { name: 'aliceList' }, alice)).body; + aliceNote = await post(alice, { text: 'test' }); bob = await signup({ username: 'bob' }); - bobNote = await post(bob, { text: 'test' }) as any; + bobNote = await post(bob, { text: 'test' }); carol = await signup({ username: 'carol' }); - dave = await signup({ username: 'dave' }); - ellen = await signup({ username: 'ellen' }); - frank = await signup({ username: 'frank' }); // @alice -> @replyingへのリプライ。Promise.allで一気に作るとtimeoutしてしまうのでreduceで一つ一つawaitする usersReplying = await [...Array(10)].map((_, i) => i).reduce(async (acc, i) => { @@ -241,7 +215,7 @@ describe('ユーザー', () => { } return (await acc).concat(u); - }, Promise.resolve([] as User[])); + }, Promise.resolve([] as misskey.entities.SignupResponse[])); userNoNote = await signup({ username: 'userNoNote' }); userNotExplorable = await signup({ username: 'userNotExplorable' }); @@ -309,7 +283,7 @@ describe('ユーザー', () => { beforeEach(async () => { alice = { ...alice, - ...await successfulApiCall({ endpoint: 'i', parameters: {}, user: alice }) as any, + ...await successfulApiCall({ endpoint: 'i', parameters: {}, user: alice }), }; aliceNote = await successfulApiCall({ endpoint: 'notes/show', parameters: { noteId: aliceNote.id }, user: alice }); }); @@ -322,7 +296,7 @@ describe('ユーザー', () => { endpoint: 'signup', parameters: { username: 'zoe', password: 'password' }, user: undefined, - }) as unknown as User; // BUG MeDetailedに足りないキーがある + }) as unknown as misskey.entities.SignupResponse; // BUG MeDetailedに足りないキーがある // signupの時はtokenが含まれる特別なMeDetailedが返ってくる assert.match(response.token, /[a-zA-Z0-9]{16}/); @@ -332,7 +306,7 @@ describe('ユーザー', () => { assert.strictEqual(response.name, null); assert.strictEqual(response.username, 'zoe'); assert.strictEqual(response.host, null); - assert.match(response.avatarUrl, /^[-a-zA-Z0-9@:%._\+~#&?=\/]+$/); + response.avatarUrl && assert.match(response.avatarUrl, /^[-a-zA-Z0-9@:%._\+~#&?=\/]+$/); assert.strictEqual(response.avatarBlurhash, null); assert.deepStrictEqual(response.avatarDecorations, []); assert.strictEqual(response.isBot, false); @@ -407,6 +381,7 @@ describe('ユーザー', () => { assert.deepStrictEqual(response.unreadAnnouncements, []); assert.deepStrictEqual(response.mutedWords, []); assert.deepStrictEqual(response.mutedInstances, []); + // @ts-expect-error 後方互換のため assert.deepStrictEqual(response.mutingNotificationTypes, []); assert.deepStrictEqual(response.notificationRecieveConfig, {}); assert.deepStrictEqual(response.emailNotificationTypes, ['follow', 'receiveFollowRequest']); @@ -436,68 +411,66 @@ describe('ユーザー', () => { //#region 自分の情報の更新(i/update) test.each([ - { parameters: (): object => ({ name: null }) }, - { parameters: (): object => ({ name: 'x'.repeat(50) }) }, - { parameters: (): object => ({ name: 'x' }) }, - { parameters: (): object => ({ name: 'My name' }) }, - { parameters: (): object => ({ description: null }) }, - { parameters: (): object => ({ description: 'x'.repeat(1500) }) }, - { parameters: (): object => ({ description: 'x' }) }, - { parameters: (): object => ({ description: 'My description' }) }, - { parameters: (): object => ({ location: null }) }, - { parameters: (): object => ({ location: 'x'.repeat(50) }) }, - { parameters: (): object => ({ location: 'x' }) }, - { parameters: (): object => ({ location: 'My location' }) }, - { parameters: (): object => ({ birthday: '0000-00-00' }) }, - { parameters: (): object => ({ birthday: '9999-99-99' }) }, - { parameters: (): object => ({ lang: 'en-US' }) }, - { parameters: (): object => ({ fields: [] }) }, - { parameters: (): object => ({ fields: [{ name: 'x', value: 'x' }] }) }, - { parameters: (): object => ({ fields: [{ name: 'x'.repeat(3000), value: 'x'.repeat(3000) }] }) }, // BUG? fieldには制限がない - { parameters: (): object => ({ fields: Array(16).fill({ name: 'x', value: 'y' }) }) }, - { parameters: (): object => ({ isLocked: true }) }, - { parameters: (): object => ({ isLocked: false }) }, - { parameters: (): object => ({ isExplorable: false }) }, - { parameters: (): object => ({ isExplorable: true }) }, - { parameters: (): object => ({ hideOnlineStatus: true }) }, - { parameters: (): object => ({ hideOnlineStatus: false }) }, - { parameters: (): object => ({ publicReactions: false }) }, - { parameters: (): object => ({ publicReactions: true }) }, - { parameters: (): object => ({ autoAcceptFollowed: true }) }, - { parameters: (): object => ({ autoAcceptFollowed: false }) }, - { parameters: (): object => ({ noCrawle: true }) }, - { parameters: (): object => ({ noCrawle: false }) }, - { parameters: (): object => ({ preventAiLearning: false }) }, - { parameters: (): object => ({ preventAiLearning: true }) }, - { parameters: (): object => ({ isBot: true }) }, - { parameters: (): object => ({ isBot: false }) }, - { parameters: (): object => ({ isCat: true }) }, - { parameters: (): object => ({ isCat: false }) }, - { parameters: (): object => ({ speakAsCat: true }) }, - { parameters: (): object => ({ speakAsCat: false }) }, - { parameters: (): object => ({ injectFeaturedNote: true }) }, - { parameters: (): object => ({ injectFeaturedNote: false }) }, - { parameters: (): object => ({ receiveAnnouncementEmail: true }) }, - { parameters: (): object => ({ receiveAnnouncementEmail: false }) }, - { parameters: (): object => ({ alwaysMarkNsfw: true }) }, - { parameters: (): object => ({ alwaysMarkNsfw: false }) }, - { parameters: (): object => ({ autoSensitive: true }) }, - { parameters: (): object => ({ autoSensitive: false }) }, - { parameters: (): object => ({ followingVisibility: 'private' }) }, - { parameters: (): object => ({ followingVisibility: 'followers' }) }, - { parameters: (): object => ({ followingVisibility: 'public' }) }, - { parameters: (): object => ({ followersVisibility: 'private' }) }, - { parameters: (): object => ({ followersVisibility: 'followers' }) }, - { parameters: (): object => ({ followersVisibility: 'public' }) }, - { parameters: (): object => ({ mutedWords: Array(19).fill(['xxxxx']) }) }, - { parameters: (): object => ({ mutedWords: [['x'.repeat(194)]] }) }, - { parameters: (): object => ({ mutedWords: [] }) }, - { parameters: (): object => ({ mutedInstances: ['xxxx.xxxxx'] }) }, - { parameters: (): object => ({ mutedInstances: [] }) }, - { parameters: (): object => ({ notificationRecieveConfig: { mention: { type: 'following' } } }) }, - { parameters: (): object => ({ notificationRecieveConfig: {} }) }, - { parameters: (): object => ({ emailNotificationTypes: ['mention', 'reply', 'quote', 'follow', 'receiveFollowRequest'] }) }, - { parameters: (): object => ({ emailNotificationTypes: [] }) }, + { parameters: () => ({ name: null }) }, + { parameters: () => ({ name: 'x'.repeat(50) }) }, + { parameters: () => ({ name: 'x' }) }, + { parameters: () => ({ name: 'My name' }) }, + { parameters: () => ({ description: null }) }, + { parameters: () => ({ description: 'x'.repeat(1500) }) }, + { parameters: () => ({ description: 'x' }) }, + { parameters: () => ({ description: 'My description' }) }, + { parameters: () => ({ location: null }) }, + { parameters: () => ({ location: 'x'.repeat(50) }) }, + { parameters: () => ({ location: 'x' }) }, + { parameters: () => ({ location: 'My location' }) }, + { parameters: () => ({ birthday: '0000-00-00' }) }, + { parameters: () => ({ birthday: '9999-99-99' }) }, + { parameters: () => ({ lang: 'en-US' as const }) }, + { parameters: () => ({ fields: [] }) }, + { parameters: () => ({ fields: [{ name: 'x', value: 'x' }] }) }, + { parameters: () => ({ fields: [{ name: 'x'.repeat(3000), value: 'x'.repeat(3000) }] }) }, // BUG? fieldには制限がない + { parameters: () => ({ fields: Array(16).fill({ name: 'x', value: 'y' }) }) }, + { parameters: () => ({ isLocked: true }) }, + { parameters: () => ({ isLocked: false }) }, + { parameters: () => ({ isExplorable: false }) }, + { parameters: () => ({ isExplorable: true }) }, + { parameters: () => ({ hideOnlineStatus: true }) }, + { parameters: () => ({ hideOnlineStatus: false }) }, + { parameters: () => ({ publicReactions: false }) }, + { parameters: () => ({ publicReactions: true }) }, + { parameters: () => ({ autoAcceptFollowed: true }) }, + { parameters: () => ({ autoAcceptFollowed: false }) }, + { parameters: () => ({ noCrawle: true }) }, + { parameters: () => ({ noCrawle: false }) }, + { parameters: () => ({ preventAiLearning: false }) }, + { parameters: () => ({ preventAiLearning: true }) }, + { parameters: () => ({ isBot: true }) }, + { parameters: () => ({ isBot: false }) }, + { parameters: () => ({ isCat: true }) }, + { parameters: () => ({ isCat: false }) }, + { parameters: () => ({ injectFeaturedNote: true }) }, + { parameters: () => ({ injectFeaturedNote: false }) }, + { parameters: () => ({ receiveAnnouncementEmail: true }) }, + { parameters: () => ({ receiveAnnouncementEmail: false }) }, + { parameters: () => ({ alwaysMarkNsfw: true }) }, + { parameters: () => ({ alwaysMarkNsfw: false }) }, + { parameters: () => ({ autoSensitive: true }) }, + { parameters: () => ({ autoSensitive: false }) }, + { parameters: () => ({ followingVisibility: 'private' as const }) }, + { parameters: () => ({ followingVisibility: 'followers' as const }) }, + { parameters: () => ({ followingVisibility: 'public' as const }) }, + { parameters: () => ({ followersVisibility: 'private' as const }) }, + { parameters: () => ({ followersVisibility: 'followers' as const }) }, + { parameters: () => ({ followersVisibility: 'public' as const }) }, + { parameters: () => ({ mutedWords: Array(19).fill(['xxxxx']) }) }, + { parameters: () => ({ mutedWords: [['x'.repeat(194)]] }) }, + { parameters: () => ({ mutedWords: [] }) }, + { parameters: () => ({ mutedInstances: ['xxxx.xxxxx'] }) }, + { parameters: () => ({ mutedInstances: [] }) }, + { parameters: () => ({ notificationRecieveConfig: { mention: { type: 'following' } } }) }, + { parameters: () => ({ notificationRecieveConfig: {} }) }, + { parameters: () => ({ emailNotificationTypes: ['mention', 'reply', 'quote', 'follow', 'receiveFollowRequest'] }) }, + { parameters: () => ({ emailNotificationTypes: [] }) }, ] as const)('を書き換えることができる($#)', async ({ parameters }) => { const response = await successfulApiCall({ endpoint: 'i/update', parameters: parameters(), user: alice }); const expected = { ...meDetailed(alice, true), ...parameters() }; @@ -506,13 +479,13 @@ describe('ユーザー', () => { test('を書き換えることができる(Avatar)', async () => { const aliceFile = (await uploadFile(alice)).body; - const parameters = { avatarId: aliceFile.id }; + const parameters = { avatarId: aliceFile!.id }; const response = await successfulApiCall({ endpoint: 'i/update', parameters: parameters, user: alice }); assert.match(response.avatarUrl ?? '.', /^[-a-zA-Z0-9@:%._\+~#&?=\/]+$/); assert.match(response.avatarBlurhash ?? '.', /[ -~]{54}/); const expected = { ...meDetailed(alice, true), - avatarId: aliceFile.id, + avatarId: aliceFile!.id, avatarBlurhash: response.avatarBlurhash, avatarUrl: response.avatarUrl, }; @@ -531,13 +504,13 @@ describe('ユーザー', () => { test('を書き換えることができる(Banner)', async () => { const aliceFile = (await uploadFile(alice)).body; - const parameters = { bannerId: aliceFile.id }; + const parameters = { bannerId: aliceFile!.id }; const response = await successfulApiCall({ endpoint: 'i/update', parameters: parameters, user: alice }); assert.match(response.bannerUrl ?? '.', /^[-a-zA-Z0-9@:%._\+~#&?=\/]+$/); assert.match(response.bannerBlurhash ?? '.', /[ -~]{54}/); const expected = { ...meDetailed(alice, true), - bannerId: aliceFile.id, + bannerId: aliceFile!.id, bannerBlurhash: response.bannerBlurhash, bannerUrl: response.bannerUrl, }; @@ -556,14 +529,14 @@ describe('ユーザー', () => { test('を書き換えることができる(Background)', async () => { const aliceFile = (await uploadFile(alice)).body; - const parameters = { bannerId: aliceFile.id }; + const parameters = { bannerId: aliceFile!.id }; const response = await successfulApiCall({ endpoint: 'i/update', parameters: parameters, user: alice }); assert.match(response.backgroundUrl ?? '.', /^[-a-zA-Z0-9@:%._\+~#&?=\/]+$/); assert.match(response.backgroundBlurhash ?? '.', /[ -~]{54}/); const expected = { ...meDetailed(alice, true), - backgroundId: aliceFile.id, - backgroundBlurhash: response.baackgroundBlurhash, + backgroundId: aliceFile!.id, + backgroundBlurhash: response.backgroundBlurhash, backgroundUrl: response.backgroundUrl, }; assert.deepStrictEqual(response, expected, inspect(parameters)); @@ -612,13 +585,13 @@ describe('ユーザー', () => { //#region ユーザー(users) test.each([ - { label: 'ID昇順', parameters: { limit: 5 }, selector: (u: UserLite): string => u.id }, - { label: 'フォロワー昇順', parameters: { sort: '+follower' }, selector: (u: UserDetailedNotMe): string => String(u.followersCount) }, - { label: 'フォロワー降順', parameters: { sort: '-follower' }, selector: (u: UserDetailedNotMe): string => String(u.followersCount) }, - { label: '登録日時昇順', parameters: { sort: '+createdAt' }, selector: (u: UserDetailedNotMe): string => u.createdAt }, - { label: '登録日時降順', parameters: { sort: '-createdAt' }, selector: (u: UserDetailedNotMe): string => u.createdAt }, - { label: '投稿日時昇順', parameters: { sort: '+updatedAt' }, selector: (u: UserDetailedNotMe): string => String(u.updatedAt) }, - { label: '投稿日時降順', parameters: { sort: '-updatedAt' }, selector: (u: UserDetailedNotMe): string => String(u.updatedAt) }, + { label: 'ID昇順', parameters: { limit: 5 }, selector: (u: misskey.entities.UserLite): string => u.id }, + { label: 'フォロワー昇順', parameters: { sort: '+follower' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.followersCount) }, + { label: 'フォロワー降順', parameters: { sort: '-follower' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.followersCount) }, + { label: '登録日時昇順', parameters: { sort: '+createdAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => u.createdAt }, + { label: '登録日時降順', parameters: { sort: '-createdAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => u.createdAt }, + { label: '投稿日時昇順', parameters: { sort: '+updatedAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.updatedAt) }, + { label: '投稿日時降順', parameters: { sort: '-updatedAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.updatedAt) }, ] as const)('をリスト形式で取得することができる($label)', async ({ parameters, selector }) => { const response = await successfulApiCall({ endpoint: 'users', parameters, user: alice }); @@ -631,15 +604,15 @@ describe('ユーザー', () => { assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれない', user: (): User => userNotExplorable, excluded: true }, - { label: 'ミュートユーザーが含まれない', user: (): User => userMutedByAlice, excluded: true }, - { label: 'ブロックされているユーザーが含まれない', user: (): User => userBlockedByAlice, excluded: true }, - { label: 'ブロックしてきているユーザーが含まれる', user: (): User => userBlockingAlice, excluded: true }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - { label: 'サスペンドユーザーが含まれない', user: (): User => userSuspended, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + { label: '「見つけやすくする」がOFFのユーザーが含まれない', user: () => userNotExplorable, excluded: true }, + { label: 'ミュートユーザーが含まれない', user: () => userMutedByAlice, excluded: true }, + { label: 'ブロックされているユーザーが含まれない', user: () => userBlockedByAlice, excluded: true }, + { label: 'ブロックしてきているユーザーが含まれる', user: () => userBlockingAlice, excluded: true }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + { label: 'サスペンドユーザーが含まれない', user: () => userSuspended, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, ] as const)('をリスト形式で取得することができ、結果に$label', async ({ user, excluded }) => { const parameters = { limit: 100 }; const response = await successfulApiCall({ endpoint: 'users', parameters, user: alice }); @@ -653,39 +626,42 @@ describe('ユーザー', () => { //#region ユーザー情報(users/show) test.each([ - { label: 'ID指定で自分自身を', parameters: (): object => ({ userId: alice.id }), user: (): User => alice, type: meDetailed }, - { label: 'ID指定で他人を', parameters: (): object => ({ userId: alice.id }), user: (): User => bob, type: userDetailedNotMeWithRelations }, - { label: 'ID指定かつ未認証', parameters: (): object => ({ userId: alice.id }), user: undefined, type: userDetailedNotMe }, - { label: '@指定で自分自身を', parameters: (): object => ({ username: alice.username }), user: (): User => alice, type: meDetailed }, - { label: '@指定で他人を', parameters: (): object => ({ username: alice.username }), user: (): User => bob, type: userDetailedNotMeWithRelations }, - { label: '@指定かつ未認証', parameters: (): object => ({ username: alice.username }), user: undefined, type: userDetailedNotMe }, + { label: 'ID指定で自分自身を', parameters: () => ({ userId: alice.id }), user: () => alice, type: meDetailed }, + { label: 'ID指定で他人を', parameters: () => ({ userId: alice.id }), user: () => bob, type: userDetailedNotMeWithRelations }, + { label: 'ID指定かつ未認証', parameters: () => ({ userId: alice.id }), user: undefined, type: userDetailedNotMe }, + { label: '@指定で自分自身を', parameters: () => ({ username: alice.username }), user: () => alice, type: meDetailed }, + { label: '@指定で他人を', parameters: () => ({ username: alice.username }), user: () => bob, type: userDetailedNotMeWithRelations }, + { label: '@指定かつ未認証', parameters: () => ({ username: alice.username }), user: undefined, type: userDetailedNotMe }, ] as const)('を取得することができる($label)', async ({ parameters, user, type }) => { const response = await successfulApiCall({ endpoint: 'users/show', parameters: parameters(), user: user?.() }); const expected = type(alice); assert.deepStrictEqual(response, expected); }); test.each([ - { label: 'Administratorになっている', user: (): User => userAdmin, me: (): User => userAdmin, selector: (user: User): unknown => user.isAdmin }, - { label: '自分以外から見たときはAdministratorか判定できない', user: (): User => userAdmin, selector: (user: User): unknown => user.isAdmin, expected: (): undefined => undefined }, - { label: 'Moderatorになっている', user: (): User => userModerator, me: (): User => userModerator, selector: (user: User): unknown => user.isModerator }, - { label: '自分以外から見たときはModeratorか判定できない', user: (): User => userModerator, selector: (user: User): unknown => user.isModerator, expected: (): undefined => undefined }, - { label: 'サイレンスになっている', user: (): User => userSilenced, selector: (user: User): unknown => user.isSilenced }, - //{ label: 'サスペンドになっている', user: (): User => userSuspended, selector: (user: User): unknown => user.isSuspended }, - { label: '削除済みになっている', user: (): User => userDeletedBySelf, me: (): User => userDeletedBySelf, selector: (user: User): unknown => user.isDeleted }, - { label: '自分以外から見たときは削除済みか判定できない', user: (): User => userDeletedBySelf, selector: (user: User): unknown => user.isDeleted, expected: (): undefined => undefined }, - { label: '削除済み(byAdmin)になっている', user: (): User => userDeletedByAdmin, me: (): User => userDeletedByAdmin, selector: (user: User): unknown => user.isDeleted }, - { label: '自分以外から見たときは削除済み(byAdmin)か判定できない', user: (): User => userDeletedByAdmin, selector: (user: User): unknown => user.isDeleted, expected: (): undefined => undefined }, - { label: 'フォロー中になっている', user: (): User => userFollowedByAlice, selector: (user: User): unknown => user.isFollowing }, - { label: 'フォローされている', user: (): User => userFollowingAlice, selector: (user: User): unknown => user.isFollowed }, - { label: 'ブロック中になっている', user: (): User => userBlockedByAlice, selector: (user: User): unknown => user.isBlocking }, - { label: 'ブロックされている', user: (): User => userBlockingAlice, selector: (user: User): unknown => user.isBlocked }, - { label: 'ミュート中になっている', user: (): User => userMutedByAlice, selector: (user: User): unknown => user.isMuted }, - { label: 'リノートミュート中になっている', user: (): User => userRnMutedByAlice, selector: (user: User): unknown => user.isRenoteMuted }, - { label: 'フォローリクエスト中になっている', user: (): User => userFollowRequested, me: (): User => userFollowRequesting, selector: (user: User): unknown => user.hasPendingFollowRequestFromYou }, - { label: 'フォローリクエストされている', user: (): User => userFollowRequesting, me: (): User => userFollowRequested, selector: (user: User): unknown => user.hasPendingFollowRequestToYou }, + { label: 'Administratorになっている', user: () => userAdmin, me: () => userAdmin, selector: (user: misskey.entities.MeDetailed) => user.isAdmin }, + { label: '自分以外から見たときはAdministratorか判定できない', user: () => userAdmin, selector: (user: misskey.entities.UserDetailedNotMe) => user.isAdmin, expected: () => undefined }, + { label: 'Moderatorになっている', user: () => userModerator, me: () => userModerator, selector: (user: misskey.entities.MeDetailed) => user.isModerator }, + { label: '自分以外から見たときはModeratorか判定できない', user: () => userModerator, selector: (user: misskey.entities.UserDetailedNotMe) => user.isModerator, expected: () => undefined }, + { label: 'サイレンスになっている', user: () => userSilenced, selector: (user: misskey.entities.UserDetailed) => user.isSilenced }, + // FIXME: 落ちる + //{ label: 'サスペンドになっている', user: () => userSuspended, selector: (user: misskey.entities.UserDetailed) => user.isSuspended }, + { label: '削除済みになっている', user: () => userDeletedBySelf, me: () => userDeletedBySelf, selector: (user: misskey.entities.MeDetailed) => user.isDeleted }, + // @ts-expect-error UserDetailedNotMe doesn't include isDeleted + { label: '自分以外から見たときは削除済みか判定できない', user: () => userDeletedBySelf, selector: (user: misskey.entities.UserDetailedNotMe) => user.isDeleted, expected: () => undefined }, + { label: '削除済み(byAdmin)になっている', user: () => userDeletedByAdmin, me: () => userDeletedByAdmin, selector: (user: misskey.entities.MeDetailed) => user.isDeleted }, + // @ts-expect-error UserDetailedNotMe doesn't include isDeleted + { label: '自分以外から見たときは削除済み(byAdmin)か判定できない', user: () => userDeletedByAdmin, selector: (user: misskey.entities.UserDetailedNotMe) => user.isDeleted, expected: () => undefined }, + { label: 'フォロー中になっている', user: () => userFollowedByAlice, selector: (user: misskey.entities.UserDetailed) => user.isFollowing }, + { label: 'フォローされている', user: () => userFollowingAlice, selector: (user: misskey.entities.UserDetailed) => user.isFollowed }, + { label: 'ブロック中になっている', user: () => userBlockedByAlice, selector: (user: misskey.entities.UserDetailed) => user.isBlocking }, + { label: 'ブロックされている', user: () => userBlockingAlice, selector: (user: misskey.entities.UserDetailed) => user.isBlocked }, + { label: 'ミュート中になっている', user: () => userMutedByAlice, selector: (user: misskey.entities.UserDetailed) => user.isMuted }, + { label: 'リノートミュート中になっている', user: () => userRnMutedByAlice, selector: (user: misskey.entities.UserDetailed) => user.isRenoteMuted }, + { label: 'フォローリクエスト中になっている', user: () => userFollowRequested, me: () => userFollowRequesting, selector: (user: misskey.entities.UserDetailed) => user.hasPendingFollowRequestFromYou }, + { label: 'フォローリクエストされている', user: () => userFollowRequesting, me: () => userFollowRequested, selector: (user: misskey.entities.UserDetailed) => user.hasPendingFollowRequestToYou }, ] as const)('を取得することができ、$labelこと', async ({ user, me, selector, expected }) => { const response = await successfulApiCall({ endpoint: 'users/show', parameters: { userId: user().id }, user: me?.() ?? alice }); - assert.strictEqual(selector(response), (expected ?? ((): true => true))()); + assert.strictEqual(selector(response as any), (expected ?? ((): true => true))()); }); test('を取得することができ、Publicなロールがセットされていること', async () => { const response = await successfulApiCall({ endpoint: 'users/show', parameters: { userId: userRolePublic.id }, user: alice }); @@ -727,17 +703,18 @@ describe('ユーザー', () => { assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: (): User => userNotExplorable }, - { label: 'ミュートユーザーが含まれる', user: (): User => userMutedByAlice }, - { label: 'ブロックされているユーザーが含まれる', user: (): User => userBlockedByAlice }, - { label: 'ブロックしてきているユーザーが含まれる', user: (): User => userBlockingAlice }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - { label: 'サスペンドユーザーが(モデレーターが見るときは)含まれる', user: (): User => userSuspended, me: (): User => root }, + { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: () => userNotExplorable }, + { label: 'ミュートユーザーが含まれる', user: () => userMutedByAlice }, + { label: 'ブロックされているユーザーが含まれる', user: () => userBlockedByAlice }, + { label: 'ブロックしてきているユーザーが含まれる', user: () => userBlockingAlice }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + { label: 'サスペンドユーザーが(モデレーターが見るときは)含まれる', user: () => userSuspended, me: () => root }, // BUG サスペンドユーザーを一般ユーザーから見るとrootユーザーが返ってくる - //{ label: 'サスペンドユーザーが(一般ユーザーが見るときは)含まれない', user: (): User => userSuspended, me: (): User => bob, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + //{ label: 'サスペンドユーザーが(一般ユーザーが見るときは)含まれない', user: () => userSuspended, me: () => bob, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, + // @ts-expect-error excluded は上でコメントアウトされているので ] as const)('をID指定のリスト形式で取得することができ、結果に$label', async ({ user, me, excluded }) => { const parameters = { userIds: [user().id] }; const response = await successfulApiCall({ endpoint: 'users/show', parameters, user: me?.() ?? alice }); @@ -762,15 +739,15 @@ describe('ユーザー', () => { assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: (): User => userNotExplorable }, - { label: 'ミュートユーザーが含まれる', user: (): User => userMutedByAlice }, - { label: 'ブロックされているユーザーが含まれる', user: (): User => userBlockedByAlice }, - { label: 'ブロックしてきているユーザーが含まれる', user: (): User => userBlockingAlice }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - { label: 'サスペンドユーザーが含まれない', user: (): User => userSuspended, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: () => userNotExplorable }, + { label: 'ミュートユーザーが含まれる', user: () => userMutedByAlice }, + { label: 'ブロックされているユーザーが含まれる', user: () => userBlockedByAlice }, + { label: 'ブロックしてきているユーザーが含まれる', user: () => userBlockingAlice }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + { label: 'サスペンドユーザーが含まれない', user: () => userSuspended, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, ] as const)('を検索することができ、結果に$labelが含まれる', async ({ user, excluded }) => { const parameters = { query: user().username, limit: 1 }; const response = await successfulApiCall({ endpoint: 'users/search', parameters, user: alice }); @@ -784,30 +761,30 @@ describe('ユーザー', () => { //#region ID指定検索(users/search-by-username-and-host) test.each([ - { label: '自分', parameters: { username: 'alice' }, user: (): User[] => [alice] }, - { label: '自分かつusernameが大文字', parameters: { username: 'ALICE' }, user: (): User[] => [alice] }, - { label: 'ローカルのフォロイーでノートなし', parameters: { username: 'userFollowedByAlice' }, user: (): User[] => [userFollowedByAlice] }, - { label: 'ローカルでノートなしは検索に載らない', parameters: { username: 'userNoNote' }, user: (): User[] => [] }, - { label: 'ローカルの他人1', parameters: { username: 'bob' }, user: (): User[] => [bob] }, - { label: 'ローカルの他人2', parameters: { username: 'bob', host: null }, user: (): User[] => [bob] }, - { label: 'ローカルの他人3', parameters: { username: 'bob', host: '.' }, user: (): User[] => [bob] }, - { label: 'ローカル', parameters: { host: null, limit: 1 }, user: (): User[] => [userFollowedByAlice] }, - { label: 'ローカル', parameters: { host: '.', limit: 1 }, user: (): User[] => [userFollowedByAlice] }, + { label: '自分', parameters: { username: 'alice' }, user: () => [alice] }, + { label: '自分かつusernameが大文字', parameters: { username: 'ALICE' }, user: () => [alice] }, + { label: 'ローカルのフォロイーでノートなし', parameters: { username: 'userFollowedByAlice' }, user: () => [userFollowedByAlice] }, + { label: 'ローカルでノートなしは検索に載らない', parameters: { username: 'userNoNote' }, user: () => [] }, + { label: 'ローカルの他人1', parameters: { username: 'bob' }, user: () => [bob] }, + { label: 'ローカルの他人2', parameters: { username: 'bob', host: null }, user: () => [bob] }, + { label: 'ローカルの他人3', parameters: { username: 'bob', host: '.' }, user: () => [bob] }, + { label: 'ローカル', parameters: { host: null, limit: 1 }, user: () => [userFollowedByAlice] }, + { label: 'ローカル', parameters: { host: '.', limit: 1 }, user: () => [userFollowedByAlice] }, ])('をID&ホスト指定で検索できる($label)', async ({ parameters, user }) => { const response = await successfulApiCall({ endpoint: 'users/search-by-username-and-host', parameters, user: alice }); const expected = await Promise.all(user().map(u => show(u.id, alice))); assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: (): User => userNotExplorable }, - { label: 'ミュートユーザーが含まれる', user: (): User => userMutedByAlice }, - { label: 'ブロックされているユーザーが含まれる', user: (): User => userBlockedByAlice }, - { label: 'ブロックしてきているユーザーが含まれる', user: (): User => userBlockingAlice }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - { label: 'サスペンドユーザーが含まれない', user: (): User => userSuspended, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: () => userNotExplorable }, + { label: 'ミュートユーザーが含まれる', user: () => userMutedByAlice }, + { label: 'ブロックされているユーザーが含まれる', user: () => userBlockedByAlice }, + { label: 'ブロックしてきているユーザーが含まれる', user: () => userBlockingAlice }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + { label: 'サスペンドユーザーが含まれない', user: () => userSuspended, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, ] as const)('をID&ホスト指定で検索でき、結果に$label', async ({ user, excluded }) => { const parameters = { username: user().username }; const response = await successfulApiCall({ endpoint: 'users/search-by-username-and-host', parameters, user: alice }); @@ -829,15 +806,15 @@ describe('ユーザー', () => { assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: (): User => userNotExplorable }, - { label: 'ミュートユーザーが含まれる', user: (): User => userMutedByAlice }, - { label: 'ブロックされているユーザーが含まれる', user: (): User => userBlockedByAlice }, - { label: 'ブロックしてきているユーザーが含まれない', user: (): User => userBlockingAlice, excluded: true }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - //{ label: 'サスペンドユーザーが含まれない', user: (): User => userSuspended, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: () => userNotExplorable }, + { label: 'ミュートユーザーが含まれる', user: () => userMutedByAlice }, + { label: 'ブロックされているユーザーが含まれる', user: () => userBlockedByAlice }, + { label: 'ブロックしてきているユーザーが含まれない', user: () => userBlockingAlice, excluded: true }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + //{ label: 'サスペンドユーザーが含まれない', user: () => userSuspended, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, ] as const)('がよくリプライをするユーザーのリストを取得でき、結果に$label', async ({ user, excluded }) => { const replyTo = (await successfulApiCall({ endpoint: 'users/notes', parameters: { userId: user().id }, user: undefined }))[0]; await post(alice, { text: `@${user().username} test`, replyId: replyTo.id }); @@ -851,12 +828,12 @@ describe('ユーザー', () => { //#region ハッシュタグ(hashtags/users) test.each([ - { label: 'フォロワー昇順', sort: { sort: '+follower' }, selector: (u: UserDetailedNotMe): string => String(u.followersCount) }, - { label: 'フォロワー降順', sort: { sort: '-follower' }, selector: (u: UserDetailedNotMe): string => String(u.followersCount) }, - { label: '登録日時昇順', sort: { sort: '+createdAt' }, selector: (u: UserDetailedNotMe): string => u.createdAt }, - { label: '登録日時降順', sort: { sort: '-createdAt' }, selector: (u: UserDetailedNotMe): string => u.createdAt }, - { label: '投稿日時昇順', sort: { sort: '+updatedAt' }, selector: (u: UserDetailedNotMe): string => String(u.updatedAt) }, - { label: '投稿日時降順', sort: { sort: '-updatedAt' }, selector: (u: UserDetailedNotMe): string => String(u.updatedAt) }, + { label: 'フォロワー昇順', sort: { sort: '+follower' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.followersCount) }, + { label: 'フォロワー降順', sort: { sort: '-follower' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.followersCount) }, + { label: '登録日時昇順', sort: { sort: '+createdAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => u.createdAt }, + { label: '登録日時降順', sort: { sort: '-createdAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => u.createdAt }, + { label: '投稿日時昇順', sort: { sort: '+updatedAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.updatedAt) }, + { label: '投稿日時降順', sort: { sort: '-updatedAt' }, selector: (u: misskey.entities.UserDetailedNotMe): string => String(u.updatedAt) }, ] as const)('をハッシュタグ指定で取得することができる($label)', async ({ sort, selector }) => { const hashtag = 'test_hashtag'; await successfulApiCall({ endpoint: 'i/update', parameters: { description: `#${hashtag}` }, user: alice }); @@ -870,15 +847,15 @@ describe('ユーザー', () => { assert.deepStrictEqual(response, expected); }); test.each([ - { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: (): User => userNotExplorable }, - { label: 'ミュートユーザーが含まれる', user: (): User => userMutedByAlice }, - { label: 'ブロックされているユーザーが含まれる', user: (): User => userBlockedByAlice }, - { label: 'ブロックしてきているユーザーが含まれる', user: (): User => userBlockingAlice }, - { label: '承認制ユーザーが含まれる', user: (): User => userLocking }, - { label: 'サイレンスユーザーが含まれる', user: (): User => userSilenced }, - { label: 'サスペンドユーザーが含まれない', user: (): User => userSuspended, excluded: true }, - { label: '削除済ユーザーが含まれる', user: (): User => userDeletedBySelf }, - { label: '削除済(byAdmin)ユーザーが含まれる', user: (): User => userDeletedByAdmin }, + { label: '「見つけやすくする」がOFFのユーザーが含まれる', user: () => userNotExplorable }, + { label: 'ミュートユーザーが含まれる', user: () => userMutedByAlice }, + { label: 'ブロックされているユーザーが含まれる', user: () => userBlockedByAlice }, + { label: 'ブロックしてきているユーザーが含まれる', user: () => userBlockingAlice }, + { label: '承認制ユーザーが含まれる', user: () => userLocking }, + { label: 'サイレンスユーザーが含まれる', user: () => userSilenced }, + { label: 'サスペンドユーザーが含まれない', user: () => userSuspended, excluded: true }, + { label: '削除済ユーザーが含まれる', user: () => userDeletedBySelf }, + { label: '削除済(byAdmin)ユーザーが含まれる', user: () => userDeletedByAdmin }, ] as const)('をハッシュタグ指定で取得することができ、結果に$label', async ({ user, excluded }) => { const hashtag = `user_test${user().username}`; if (user() !== userSuspended) { diff --git a/packages/backend/test/global.d.ts b/packages/backend/test/global.d.ts new file mode 100644 index 0000000000..0363073356 --- /dev/null +++ b/packages/backend/test/global.d.ts @@ -0,0 +1,7 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type FIXME = any; diff --git a/packages/backend/test/jest.setup.ts b/packages/backend/test/jest.setup.ts index cf5b9bf24d..861bc6db66 100644 --- a/packages/backend/test/jest.setup.ts +++ b/packages/backend/test/jest.setup.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { initTestDb, sendEnvResetRequest } from './utils.js'; beforeAll(async () => { diff --git a/packages/backend/test/prelude/get-api-validator.ts b/packages/backend/test/prelude/get-api-validator.ts index b86a7a978d..7aa7a92702 100644 --- a/packages/backend/test/prelude/get-api-validator.ts +++ b/packages/backend/test/prelude/get-api-validator.ts @@ -4,10 +4,10 @@ */ import Ajv from 'ajv'; -import { Schema } from '@/misc/schema'; +import { Schema } from '@/misc/json-schema.js'; export const getValidator = (paramDef: Schema) => { - const ajv = new Ajv({ + const ajv = new Ajv.default({ useDefaults: true, }); ajv.addFormat('misskey:id', /^[a-zA-Z0-9]+$/); diff --git a/packages/backend/test/resources/kick_gaba7.m4a b/packages/backend/test/resources/kick_gaba7.m4a new file mode 100644 index 0000000000..321df6349f Binary files /dev/null and b/packages/backend/test/resources/kick_gaba7.m4a differ diff --git a/packages/backend/test/tsconfig.json b/packages/backend/test/tsconfig.json index 4597ff8780..2b562acda8 100644 --- a/packages/backend/test/tsconfig.json +++ b/packages/backend/test/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitAny": true, "noImplicitReturns": true, "noUnusedParameters": false, - "noUnusedLocals": true, + "noUnusedLocals": false, "noFallthroughCasesInSwitch": true, "declaration": false, "sourceMap": true, @@ -18,6 +18,7 @@ "strict": true, "strictNullChecks": true, "strictPropertyInitialization": false, + "skipLibCheck": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "resolveJsonModule": true, diff --git a/packages/backend/test/unit/AnnouncementService.ts b/packages/backend/test/unit/AnnouncementService.ts index fc35837420..81da0fac31 100644 --- a/packages/backend/test/unit/AnnouncementService.ts +++ b/packages/backend/test/unit/AnnouncementService.ts @@ -10,6 +10,7 @@ import { ModuleMocker } from 'jest-mock'; import { Test } from '@nestjs/testing'; import { GlobalModule } from '@/GlobalModule.js'; import { AnnouncementService } from '@/core/AnnouncementService.js'; +import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js'; import type { AnnouncementReadsRepository, AnnouncementsRepository, @@ -51,7 +52,7 @@ describe('AnnouncementService', () => { function createAnnouncement(data: Partial = {}) { return announcementsRepository.insert({ - id: genAidx(data.createdAt ?? new Date()), + id: genAidx(data.createdAt?.getTime() ?? Date.now()), updatedAt: null, title: 'Title', text: 'Text', @@ -67,6 +68,7 @@ describe('AnnouncementService', () => { ], providers: [ AnnouncementService, + AnnouncementEntityService, CacheService, IdService, ], diff --git a/packages/backend/test/unit/ApMfmService.ts b/packages/backend/test/unit/ApMfmService.ts index 2b79041c86..79cb81f5c9 100644 --- a/packages/backend/test/unit/ApMfmService.ts +++ b/packages/backend/test/unit/ApMfmService.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import * as assert from 'assert'; import { Test } from '@nestjs/testing'; diff --git a/packages/backend/test/unit/FetchInstanceMetadataService.ts b/packages/backend/test/unit/FetchInstanceMetadataService.ts index e6e68ccd6d..bf8f3ab0e3 100644 --- a/packages/backend/test/unit/FetchInstanceMetadataService.ts +++ b/packages/backend/test/unit/FetchInstanceMetadataService.ts @@ -19,8 +19,8 @@ import { DI } from '@/di-symbols.js'; import type { TestingModule } from '@nestjs/testing'; function mockRedis() { - const hash = {}; - const set = jest.fn((key, value) => { + const hash = {} as any; + const set = jest.fn((key: string, value) => { const ret = hash[key]; hash[key] = value; return ret; @@ -56,12 +56,13 @@ describe('FetchInstanceMetadataService', () => { } else if (token === DI.redis) { return mockRedis; } + return null; }) .compile(); app.enableShutdownHooks(); - fetchInstanceMetadataService = app.get(FetchInstanceMetadataService); + fetchInstanceMetadataService = app.get(FetchInstanceMetadataService) as jest.Mocked; federatedInstanceService = app.get(FederatedInstanceService) as jest.Mocked; redisClient = app.get(DI.redis) as jest.Mocked; httpRequestService = app.get(HttpRequestService) as jest.Mocked; @@ -74,11 +75,12 @@ describe('FetchInstanceMetadataService', () => { test('Lock and update', async () => { redisClient.set = mockRedis(); const now = Date.now(); - federatedInstanceService.fetch.mockReturnValue({ infoUpdatedAt: { getTime: () => { return now - 10 * 1000 * 60 * 60 * 24; } } }); + federatedInstanceService.fetch.mockResolvedValue({ infoUpdatedAt: { getTime: () => { return now - 10 * 1000 * 60 * 60 * 24; } } } as any); httpRequestService.getJson.mockImplementation(() => { throw Error(); }); const tryLockSpy = jest.spyOn(fetchInstanceMetadataService, 'tryLock'); const unlockSpy = jest.spyOn(fetchInstanceMetadataService, 'unlock'); - await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' }); + + await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' } as any); expect(tryLockSpy).toHaveBeenCalledTimes(1); expect(unlockSpy).toHaveBeenCalledTimes(1); expect(federatedInstanceService.fetch).toHaveBeenCalledTimes(1); @@ -88,11 +90,12 @@ describe('FetchInstanceMetadataService', () => { test('Lock and don\'t update', async () => { redisClient.set = mockRedis(); const now = Date.now(); - federatedInstanceService.fetch.mockReturnValue({ infoUpdatedAt: { getTime: () => now } }); + federatedInstanceService.fetch.mockResolvedValue({ infoUpdatedAt: { getTime: () => now } } as any); httpRequestService.getJson.mockImplementation(() => { throw Error(); }); const tryLockSpy = jest.spyOn(fetchInstanceMetadataService, 'tryLock'); const unlockSpy = jest.spyOn(fetchInstanceMetadataService, 'unlock'); - await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' }); + + await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' } as any); expect(tryLockSpy).toHaveBeenCalledTimes(1); expect(unlockSpy).toHaveBeenCalledTimes(1); expect(federatedInstanceService.fetch).toHaveBeenCalledTimes(1); @@ -101,15 +104,33 @@ describe('FetchInstanceMetadataService', () => { test('Do nothing when lock not acquired', async () => { redisClient.set = mockRedis(); - federatedInstanceService.fetch.mockReturnValue({ infoUpdatedAt: { getTime: () => now - 10 * 1000 * 60 * 60 * 24 } }); + const now = Date.now(); + federatedInstanceService.fetch.mockResolvedValue({ infoUpdatedAt: { getTime: () => now - 10 * 1000 * 60 * 60 * 24 } } as any); httpRequestService.getJson.mockImplementation(() => { throw Error(); }); + await fetchInstanceMetadataService.tryLock('example.com'); const tryLockSpy = jest.spyOn(fetchInstanceMetadataService, 'tryLock'); const unlockSpy = jest.spyOn(fetchInstanceMetadataService, 'unlock'); - await fetchInstanceMetadataService.tryLock('example.com'); - await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' }); - expect(tryLockSpy).toHaveBeenCalledTimes(2); + + await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' } as any); + expect(tryLockSpy).toHaveBeenCalledTimes(1); expect(unlockSpy).toHaveBeenCalledTimes(0); expect(federatedInstanceService.fetch).toHaveBeenCalledTimes(0); expect(httpRequestService.getJson).toHaveBeenCalledTimes(0); }); + + test('Do when lock not acquired but forced', async () => { + redisClient.set = mockRedis(); + const now = Date.now(); + federatedInstanceService.fetch.mockResolvedValue({ infoUpdatedAt: { getTime: () => now - 10 * 1000 * 60 * 60 * 24 } } as any); + httpRequestService.getJson.mockImplementation(() => { throw Error(); }); + await fetchInstanceMetadataService.tryLock('example.com'); + const tryLockSpy = jest.spyOn(fetchInstanceMetadataService, 'tryLock'); + const unlockSpy = jest.spyOn(fetchInstanceMetadataService, 'unlock'); + + await fetchInstanceMetadataService.fetchInstanceMetadata({ host: 'example.com' } as any, true); + expect(tryLockSpy).toHaveBeenCalledTimes(0); + expect(unlockSpy).toHaveBeenCalledTimes(1); + expect(federatedInstanceService.fetch).toHaveBeenCalledTimes(0); + expect(httpRequestService.getJson).toHaveBeenCalled(); + }); }); diff --git a/packages/backend/test/unit/FileInfoService.ts b/packages/backend/test/unit/FileInfoService.ts index 7d89886064..bfe7143aa4 100644 --- a/packages/backend/test/unit/FileInfoService.ts +++ b/packages/backend/test/unit/FileInfoService.ts @@ -14,6 +14,7 @@ import { afterAll, beforeAll, describe, test } from '@jest/globals'; import { GlobalModule } from '@/GlobalModule.js'; import { FileInfoService } from '@/core/FileInfoService.js'; //import { DI } from '@/di-symbols.js'; +import { LoggerService } from '@/core/LoggerService.js'; import type { TestingModule } from '@nestjs/testing'; import type { MockFunctionMetadata } from 'jest-mock'; @@ -33,6 +34,7 @@ describe('FileInfoService', () => { GlobalModule, ], providers: [ + LoggerService, FileInfoService, ], }) @@ -318,8 +320,26 @@ describe('FileInfoService', () => { }); }); - /* - * video/webmとして検出されてしまう + test('MPEG-4 AUDIO (M4A)', async () => { + const path = `${resources}/kick_gaba7.m4a`; + const info = await fileInfoService.getFileInfo(path) as any; + delete info.warnings; + delete info.blurhash; + delete info.sensitive; + delete info.porn; + delete info.width; + delete info.height; + delete info.orientation; + assert.deepStrictEqual(info, { + size: 9817, + md5: '74c9279a4abe98789565f1dc1a541a42', + type: { + mime: 'audio/mp4', + ext: 'm4a', + }, + }); + }); + test('WEBM AUDIO', async () => { const path = `${resources}/kick_gaba7.webm`; const info = await fileInfoService.getFileInfo(path) as any; @@ -332,13 +352,12 @@ describe('FileInfoService', () => { delete info.orientation; assert.deepStrictEqual(info, { size: 8879, - md5: '3350083dec312419cfdc06c16413aca7', + md5: '53bc1adcb6acbbda67ff9bd484896438', type: { mime: 'audio/webm', ext: 'webm', }, }); }); - */ }); }); diff --git a/packages/backend/test/unit/MfmService.ts b/packages/backend/test/unit/MfmService.ts index 85242f2bc7..8d5683329f 100644 --- a/packages/backend/test/unit/MfmService.ts +++ b/packages/backend/test/unit/MfmService.ts @@ -39,6 +39,12 @@ describe('MfmService', () => { const output = '

foo bar

'; assert.equal(mfmService.toHtml(mfm.parse(input)), output); }); + + test('escape', () => { + const input = '```\n

Hello, world!

\n```'; + const output = '

<p>Hello, world!</p>

'; + assert.equal(mfmService.toHtml(mfm.parse(input)), output); + }); }); describe('fromHtml', () => { diff --git a/packages/backend/test/unit/NoteCreateService.ts b/packages/backend/test/unit/NoteCreateService.ts new file mode 100644 index 0000000000..ccf9ed1e6d --- /dev/null +++ b/packages/backend/test/unit/NoteCreateService.ts @@ -0,0 +1,145 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Test } from '@nestjs/testing'; + +import { CoreModule } from '@/core/CoreModule.js'; +import { NoteCreateService } from '@/core/NoteCreateService.js'; +import { GlobalModule } from '@/GlobalModule.js'; +import { MiNote } from '@/models/Note.js'; +import { IPoll } from '@/models/Poll.js'; +import { MiDriveFile } from '@/models/DriveFile.js'; + +describe('NoteCreateService', () => { + let noteCreateService: NoteCreateService; + + beforeAll(async () => { + const app = await Test.createTestingModule({ + imports: [GlobalModule, CoreModule], + }).compile(); + noteCreateService = app.get(NoteCreateService); + }); + + describe('is-renote', () => { + const base: MiNote = { + id: 'some-note-id', + updatedAt: null, + replyId: null, + reply: null, + renoteId: null, + renote: null, + threadId: null, + text: null, + name: null, + cw: null, + userId: 'some-user-id', + user: null, + localOnly: false, + reactionAcceptance: null, + renoteCount: 0, + repliesCount: 0, + clippedCount: 0, + reactions: {}, + visibility: 'public', + uri: null, + url: null, + fileIds: [], + attachedFileTypes: [], + visibleUserIds: [], + mentions: [], + mentionedRemoteUsers: '', + reactionAndUserPairCache: [], + emojis: [], + tags: [], + hasPoll: false, + channelId: null, + channel: null, + userHost: null, + replyUserId: null, + replyUserHost: null, + renoteUserId: null, + renoteUserHost: null, + }; + + const poll: IPoll = { + choices: ['kinoko', 'takenoko'], + multiple: false, + expiresAt: null, + }; + + const file: MiDriveFile = { + id: 'some-file-id', + userId: null, + user: null, + userHost: null, + md5: '', + name: '', + type: '', + size: 0, + comment: null, + blurhash: null, + properties: {}, + storedInternal: false, + url: '', + thumbnailUrl: null, + webpublicUrl: null, + webpublicType: null, + accessKey: null, + thumbnailAccessKey: null, + webpublicAccessKey: null, + uri: null, + src: null, + folderId: null, + folder: null, + isSensitive: false, + maybeSensitive: false, + maybePorn: false, + isLink: false, + requestHeaders: null, + requestIp: null, + }; + + test('note without renote should not be Renote', () => { + const note = { renote: null }; + expect(noteCreateService['isRenote'](note)).toBe(false); + }); + + test('note with renote should be Renote and not be Quote', () => { + const note = { renote: base }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(false); + }); + + test('note with renote and text should be Quote', () => { + const note = { renote: base, text: 'some-text' }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(true); + }); + + test('note with renote and cw should be Quote', () => { + const note = { renote: base, cw: 'some-cw' }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(true); + }); + + test('note with renote and reply should be Quote', () => { + const note = { renote: base, reply: { ...base, id: 'another-note-id' } }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(true); + }); + + test('note with renote and poll should be Quote', () => { + const note = { renote: base, poll }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(true); + }); + + test('note with renote and non-empty files should be Quote', () => { + const note = { renote: base, files: [file] }; + expect(noteCreateService['isRenote'](note)).toBe(true); + expect(noteCreateService['isQuote'](note)).toBe(true); + }); + }); +}); diff --git a/packages/backend/test/unit/RelayService.ts b/packages/backend/test/unit/RelayService.ts index f2a67dba46..9676abf07b 100644 --- a/packages/backend/test/unit/RelayService.ts +++ b/packages/backend/test/unit/RelayService.ts @@ -90,7 +90,8 @@ describe('RelayService', () => { expect(queueService.deliver).toHaveBeenCalled(); expect(queueService.deliver.mock.lastCall![1]?.type).toBe('Undo'); - expect(queueService.deliver.mock.lastCall![1]?.object.type).toBe('Follow'); + expect(typeof queueService.deliver.mock.lastCall![1]?.object).toBe('object'); + expect((queueService.deliver.mock.lastCall![1]?.object as any).type).toBe('Follow'); expect(queueService.deliver.mock.lastCall![2]).toBe('https://example.com'); //expect(queueService.deliver.mock.lastCall![0].username).toBe('relay.actor'); diff --git a/packages/backend/test/unit/RoleService.ts b/packages/backend/test/unit/RoleService.ts index fe5ad31597..ec441735d7 100644 --- a/packages/backend/test/unit/RoleService.ts +++ b/packages/backend/test/unit/RoleService.ts @@ -3,6 +3,8 @@ * SPDX-License-Identifier: AGPL-3.0-only */ +import { UserEntityService } from '@/core/entities/UserEntityService.js'; + process.env.NODE_ENV = 'test'; import { jest } from '@jest/globals'; @@ -20,6 +22,7 @@ import { IdService } from '@/core/IdService.js'; import { GlobalEventService } from '@/core/GlobalEventService.js'; import { secureRndstr } from '@/misc/secure-rndstr.js'; import { NotificationService } from '@/core/NotificationService.js'; +import { RoleCondFormulaValue } from '@/models/Role.js'; import { sleep } from '../utils.js'; import type { TestingModule } from '@nestjs/testing'; import type { MockFunctionMetadata } from 'jest-mock'; @@ -52,12 +55,26 @@ describe('RoleService', () => { id: genAidx(Date.now()), updatedAt: new Date(), lastUsedAt: new Date(), + name: '', description: '', ...data, }) .then(x => rolesRepository.findOneByOrFail(x.identifiers[0])); } + function createConditionalRole(condFormula: RoleCondFormulaValue, data: Partial = {}) { + return createRole({ + name: `[conditional] ${condFormula.type}`, + target: 'conditional', + condFormula: condFormula, + ...data, + }); + } + + function aidx() { + return genAidx(Date.now()); + } + beforeEach(async () => { clock = lolex.install({ now: new Date(), @@ -73,6 +90,7 @@ describe('RoleService', () => { CacheService, IdService, GlobalEventService, + UserEntityService, { provide: NotificationService, useFactory: () => ({ @@ -209,76 +227,6 @@ describe('RoleService', () => { expect(result.driveCapacityMb).toBe(100); }); - test('conditional role', async () => { - const user1 = await createUser({ - id: genAidx(Date.now() - (1000 * 60 * 60 * 24 * 365)), - }); - const user2 = await createUser({ - id: genAidx(Date.now() - (1000 * 60 * 60 * 24 * 365)), - followersCount: 10, - }); - await createRole({ - name: 'a', - policies: { - canManageCustomEmojis: { - useDefault: false, - priority: 0, - value: true, - }, - }, - target: 'conditional', - condFormula: { - type: 'and', - values: [{ - type: 'followersMoreThanOrEq', - value: 10, - }, { - type: 'createdMoreThan', - sec: 60 * 60 * 24 * 7, - }], - }, - }); - - metaService.fetch.mockResolvedValue({ - policies: { - canManageCustomEmojis: false, - }, - } as any); - - const user1Policies = await roleService.getUserPolicies(user1.id); - const user2Policies = await roleService.getUserPolicies(user2.id); - expect(user1Policies.canManageCustomEmojis).toBe(false); - expect(user2Policies.canManageCustomEmojis).toBe(true); - }); - - test('コンディショナルロール: マニュアルロールにアサイン済み', async () => { - const [user1, user2, role1] = await Promise.all([ - createUser(), - createUser(), - createRole({ - name: 'manual role', - }), - ]); - const role2 = await createRole({ - name: 'conditional role', - target: 'conditional', - condFormula: { - // idはバックエンドのロジックに必要ない? - id: 'bdc612bd-9d54-4675-ae83-0499c82ea670', - type: 'roleAssignedTo', - roleId: role1.id, - }, - }); - await roleService.assign(user2.id, role1.id); - - const [u1role, u2role] = await Promise.all([ - roleService.getUserRoles(user1.id), - roleService.getUserRoles(user2.id), - ]); - expect(u1role.some(r => r.id === role2.id)).toBe(false); - expect(u2role.some(r => r.id === role2.id)).toBe(true); - }); - test('expired role', async () => { const user = await createUser(); const role = await createRole({ @@ -317,6 +265,427 @@ describe('RoleService', () => { }); }); + describe('conditional role', () => { + test('~かつ~', async () => { + const [user1, user2, user3, user4] = await Promise.all([ + createUser({ isBot: true, isCat: false, isSuspended: false }), + createUser({ isBot: false, isCat: true, isSuspended: false }), + createUser({ isBot: true, isCat: true, isSuspended: false }), + createUser({ isBot: false, isCat: false, isSuspended: true }), + ]); + const role1 = await createConditionalRole({ + id: aidx(), + type: 'isBot', + }); + const role2 = await createConditionalRole({ + id: aidx(), + type: 'isCat', + }); + const role3 = await createConditionalRole({ + id: aidx(), + type: 'isSuspended', + }); + const role4 = await createConditionalRole({ + id: aidx(), + type: 'and', + values: [role1.condFormula, role2.condFormula], + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + const actual4 = await roleService.getUserRoles(user4.id); + expect(actual1.some(r => r.id === role4.id)).toBe(false); + expect(actual2.some(r => r.id === role4.id)).toBe(false); + expect(actual3.some(r => r.id === role4.id)).toBe(true); + expect(actual4.some(r => r.id === role4.id)).toBe(false); + }); + + test('~または~', async () => { + const [user1, user2, user3, user4] = await Promise.all([ + createUser({ isBot: true, isCat: false, isSuspended: false }), + createUser({ isBot: false, isCat: true, isSuspended: false }), + createUser({ isBot: true, isCat: true, isSuspended: false }), + createUser({ isBot: false, isCat: false, isSuspended: true }), + ]); + const role1 = await createConditionalRole({ + id: aidx(), + type: 'isBot', + }); + const role2 = await createConditionalRole({ + id: aidx(), + type: 'isCat', + }); + const role3 = await createConditionalRole({ + id: aidx(), + type: 'isSuspended', + }); + const role4 = await createConditionalRole({ + id: aidx(), + type: 'or', + values: [role1.condFormula, role2.condFormula], + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + const actual4 = await roleService.getUserRoles(user4.id); + expect(actual1.some(r => r.id === role4.id)).toBe(true); + expect(actual2.some(r => r.id === role4.id)).toBe(true); + expect(actual3.some(r => r.id === role4.id)).toBe(true); + expect(actual4.some(r => r.id === role4.id)).toBe(false); + }); + + test('~ではない', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ isBot: true, isCat: false, isSuspended: false }), + createUser({ isBot: false, isCat: true, isSuspended: false }), + createUser({ isBot: true, isCat: true, isSuspended: false }), + ]); + const role1 = await createConditionalRole({ + id: aidx(), + type: 'isBot', + }); + const role2 = await createConditionalRole({ + id: aidx(), + type: 'isCat', + }); + const role4 = await createConditionalRole({ + id: aidx(), + type: 'not', + value: role1.condFormula, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role4.id)).toBe(false); + expect(actual2.some(r => r.id === role4.id)).toBe(true); + expect(actual3.some(r => r.id === role4.id)).toBe(false); + }); + + test('マニュアルロールにアサイン済み', async () => { + const [user1, user2, role1] = await Promise.all([ + createUser(), + createUser(), + createRole({ + name: 'manual role', + }), + ]); + const role2 = await createConditionalRole({ + id: aidx(), + type: 'roleAssignedTo', + roleId: role1.id, + }); + await roleService.assign(user2.id, role1.id); + + const [u1role, u2role] = await Promise.all([ + roleService.getUserRoles(user1.id), + roleService.getUserRoles(user2.id), + ]); + expect(u1role.some(r => r.id === role2.id)).toBe(false); + expect(u2role.some(r => r.id === role2.id)).toBe(true); + }); + + test('ローカルユーザのみ', async () => { + const [user1, user2] = await Promise.all([ + createUser({ host: null }), + createUser({ host: 'example.com' }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isLocal', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(true); + expect(actual2.some(r => r.id === role.id)).toBe(false); + }); + + test('リモートユーザのみ', async () => { + const [user1, user2] = await Promise.all([ + createUser({ host: null }), + createUser({ host: 'example.com' }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isRemote', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('サスペンド済みユーザである', async () => { + const [user1, user2] = await Promise.all([ + createUser({ isSuspended: false }), + createUser({ isSuspended: true }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isSuspended', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('鍵アカウントユーザである', async () => { + const [user1, user2] = await Promise.all([ + createUser({ isLocked: false }), + createUser({ isLocked: true }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isLocked', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('botユーザである', async () => { + const [user1, user2] = await Promise.all([ + createUser({ isBot: false }), + createUser({ isBot: true }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isBot', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('猫である', async () => { + const [user1, user2] = await Promise.all([ + createUser({ isCat: false }), + createUser({ isCat: true }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isCat', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('「ユーザを見つけやすくする」が有効なアカウント', async () => { + const [user1, user2] = await Promise.all([ + createUser({ isExplorable: false }), + createUser({ isExplorable: true }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'isExplorable', + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + }); + + test('ユーザが作成されてから指定期間経過した', async () => { + const base = new Date(); + base.setMinutes(base.getMinutes() - 5); + + const d1 = new Date(base); + const d2 = new Date(base); + const d3 = new Date(base); + d1.setSeconds(d1.getSeconds() - 1); + d3.setSeconds(d3.getSeconds() + 1); + + const [user1, user2, user3] = await Promise.all([ + // 4:59 + createUser({ id: genAidx(d1.getTime()) }), + // 5:00 + createUser({ id: genAidx(d2.getTime()) }), + // 5:01 + createUser({ id: genAidx(d3.getTime()) }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'createdLessThan', + // 5 minutes + sec: 300, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(false); + expect(actual3.some(r => r.id === role.id)).toBe(true); + }); + + test('ユーザが作成されてから指定期間経っていない', async () => { + const base = new Date(); + base.setMinutes(base.getMinutes() - 5); + + const d1 = new Date(base); + const d2 = new Date(base); + const d3 = new Date(base); + d1.setSeconds(d1.getSeconds() - 1); + d3.setSeconds(d3.getSeconds() + 1); + + const [user1, user2, user3] = await Promise.all([ + // 4:59 + createUser({ id: genAidx(d1.getTime()) }), + // 5:00 + createUser({ id: genAidx(d2.getTime()) }), + // 5:01 + createUser({ id: genAidx(d3.getTime()) }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'createdMoreThan', + // 5 minutes + sec: 300, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(true); + expect(actual2.some(r => r.id === role.id)).toBe(false); + expect(actual3.some(r => r.id === role.id)).toBe(false); + }); + + test('フォロワー数が指定値以下', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ followersCount: 99 }), + createUser({ followersCount: 100 }), + createUser({ followersCount: 101 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'followersLessThanOrEq', + value: 100, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(true); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(false); + }); + + test('フォロワー数が指定値以下', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ followersCount: 99 }), + createUser({ followersCount: 100 }), + createUser({ followersCount: 101 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'followersMoreThanOrEq', + value: 100, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(true); + }); + + test('フォロー数が指定値以下', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ followingCount: 99 }), + createUser({ followingCount: 100 }), + createUser({ followingCount: 101 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'followingLessThanOrEq', + value: 100, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(true); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(false); + }); + + test('フォロー数が指定値以上', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ followingCount: 99 }), + createUser({ followingCount: 100 }), + createUser({ followingCount: 101 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'followingMoreThanOrEq', + value: 100, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(true); + }); + + test('ノート数が指定値以下', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ notesCount: 9 }), + createUser({ notesCount: 10 }), + createUser({ notesCount: 11 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'notesLessThanOrEq', + value: 10, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(true); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(false); + }); + + test('ノート数が指定値以上', async () => { + const [user1, user2, user3] = await Promise.all([ + createUser({ notesCount: 9 }), + createUser({ notesCount: 10 }), + createUser({ notesCount: 11 }), + ]); + const role = await createConditionalRole({ + id: aidx(), + type: 'notesMoreThanOrEq', + value: 10, + }); + + const actual1 = await roleService.getUserRoles(user1.id); + const actual2 = await roleService.getUserRoles(user2.id); + const actual3 = await roleService.getUserRoles(user3.id); + expect(actual1.some(r => r.id === role.id)).toBe(false); + expect(actual2.some(r => r.id === role.id)).toBe(true); + expect(actual3.some(r => r.id === role.id)).toBe(true); + }); + }); + describe('assign', () => { test('公開ロールの場合は通知される', async () => { const user = await createUser(); diff --git a/packages/backend/test/unit/activitypub.ts b/packages/backend/test/unit/activitypub.ts index bd335bb2fe..2e80b64a9f 100644 --- a/packages/backend/test/unit/activitypub.ts +++ b/packages/backend/test/unit/activitypub.ts @@ -13,11 +13,13 @@ import { ApImageService } from '@/core/activitypub/models/ApImageService.js'; import { ApNoteService } from '@/core/activitypub/models/ApNoteService.js'; import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js'; import { ApRendererService } from '@/core/activitypub/ApRendererService.js'; +import { JsonLdService } from '@/core/activitypub/JsonLdService.js'; +import { CONTEXT } from '@/core/activitypub/misc/contexts.js'; import { GlobalModule } from '@/GlobalModule.js'; import { CoreModule } from '@/core/CoreModule.js'; import { FederatedInstanceService } from '@/core/FederatedInstanceService.js'; import { LoggerService } from '@/core/LoggerService.js'; -import type { IActor, IApDocument, ICollection, IPost } from '@/core/activitypub/type.js'; +import type { IActor, IApDocument, ICollection, IObject, IPost } from '@/core/activitypub/type.js'; import { MiMeta, MiNote } from '@/models/_.js'; import { secureRndstr } from '@/misc/secure-rndstr.js'; import { DownloadService } from '@/core/DownloadService.js'; @@ -88,6 +90,7 @@ describe('ActivityPub', () => { let noteService: ApNoteService; let personService: ApPersonService; let rendererService: ApRendererService; + let jsonLdService: JsonLdService; let resolver: MockResolver; const metaInitial = { @@ -128,6 +131,7 @@ describe('ActivityPub', () => { personService = app.get(ApPersonService); rendererService = app.get(ApRendererService); imageService = app.get(ApImageService); + jsonLdService = app.get(JsonLdService); resolver = new MockResolver(await app.resolve(LoggerService)); // Prevent ApPersonService from fetching instance, as it causes Jest import-after-test error @@ -295,7 +299,7 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), imageObject, ); - assert.ok(!driveFile.isLink); + assert.ok(driveFile && !driveFile.isLink); const sensitiveImageObject: IApDocument = { type: 'Document', @@ -308,7 +312,7 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), sensitiveImageObject, ); - assert.ok(!sensitiveDriveFile.isLink); + assert.ok(sensitiveDriveFile && !sensitiveDriveFile.isLink); }); test('cacheRemoteFiles=false disables caching', async () => { @@ -324,7 +328,7 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), imageObject, ); - assert.ok(driveFile.isLink); + assert.ok(driveFile && driveFile.isLink); const sensitiveImageObject: IApDocument = { type: 'Document', @@ -337,7 +341,7 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), sensitiveImageObject, ); - assert.ok(sensitiveDriveFile.isLink); + assert.ok(sensitiveDriveFile && sensitiveDriveFile.isLink); }); test('cacheRemoteSensitiveFiles=false only affects sensitive files', async () => { @@ -353,7 +357,7 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), imageObject, ); - assert.ok(!driveFile.isLink); + assert.ok(driveFile && !driveFile.isLink); const sensitiveImageObject: IApDocument = { type: 'Document', @@ -366,7 +370,57 @@ describe('ActivityPub', () => { await createRandomRemoteUser(resolver, personService), sensitiveImageObject, ); - assert.ok(sensitiveDriveFile.isLink); + assert.ok(sensitiveDriveFile && sensitiveDriveFile.isLink); + }); + + test('Link is not an attachment files', async () => { + const linkObject: IObject = { + type: 'Link', + href: 'https://example.com/', + }; + const driveFile = await imageService.createImage( + await createRandomRemoteUser(resolver, personService), + linkObject, + ); + assert.strictEqual(driveFile, null); + }); + }); + + describe('JSON-LD', () =>{ + test('Compaction', async () => { + const jsonLd = jsonLdService.use(); + + const object = { + '@context': [ + 'https://www.w3.org/ns/activitystreams', + { + _misskey_quote: 'https://misskey-hub.net/ns#_misskey_quote', + unknown: 'https://example.org/ns#unknown', + undefined: null, + }, + ], + id: 'https://example.com/notes/42', + type: 'Note', + attributedTo: 'https://example.com/users/1', + to: ['https://www.w3.org/ns/activitystreams#Public'], + content: 'test test foo', + _misskey_quote: 'https://example.com/notes/1', + unknown: 'test test bar', + undefined: 'test test baz', + }; + const compacted = await jsonLd.compact(object); + + assert.deepStrictEqual(compacted, { + '@context': CONTEXT, + id: 'https://example.com/notes/42', + type: 'Note', + attributedTo: 'https://example.com/users/1', + to: 'as:Public', + content: 'test test foo', + _misskey_quote: 'https://example.com/notes/1', + 'https://example.org/ns#unknown': 'test test bar', + // undefined: 'test test baz', + }); }); }); }); diff --git a/packages/backend/test/unit/entities/UserEntityService.ts b/packages/backend/test/unit/entities/UserEntityService.ts new file mode 100644 index 0000000000..ee16d421c4 --- /dev/null +++ b/packages/backend/test/unit/entities/UserEntityService.ts @@ -0,0 +1,528 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Test, TestingModule } from '@nestjs/testing'; +import { UserEntityService } from '@/core/entities/UserEntityService.js'; +import { GlobalModule } from '@/GlobalModule.js'; +import { CoreModule } from '@/core/CoreModule.js'; +import type { MiUser } from '@/models/User.js'; +import { secureRndstr } from '@/misc/secure-rndstr.js'; +import { genAidx } from '@/misc/id/aidx.js'; +import { + BlockingsRepository, + FollowingsRepository, FollowRequestsRepository, + MiUserProfile, MutingsRepository, RenoteMutingsRepository, + UserMemoRepository, + UserProfilesRepository, + UsersRepository, +} from '@/models/_.js'; +import { DI } from '@/di-symbols.js'; +import { AvatarDecorationService } from '@/core/AvatarDecorationService.js'; +import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js'; +import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { PageEntityService } from '@/core/entities/PageEntityService.js'; +import { CustomEmojiService } from '@/core/CustomEmojiService.js'; +import { AnnouncementService } from '@/core/AnnouncementService.js'; +import { RoleService } from '@/core/RoleService.js'; +import { FederatedInstanceService } from '@/core/FederatedInstanceService.js'; +import { IdService } from '@/core/IdService.js'; +import { UtilityService } from '@/core/UtilityService.js'; +import { EmojiEntityService } from '@/core/entities/EmojiEntityService.js'; +import { ModerationLogService } from '@/core/ModerationLogService.js'; +import { GlobalEventService } from '@/core/GlobalEventService.js'; +import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js'; +import { MetaService } from '@/core/MetaService.js'; +import { FetchInstanceMetadataService } from '@/core/FetchInstanceMetadataService.js'; +import { CacheService } from '@/core/CacheService.js'; +import { ApResolverService } from '@/core/activitypub/ApResolverService.js'; +import { ApNoteService } from '@/core/activitypub/models/ApNoteService.js'; +import { ApImageService } from '@/core/activitypub/models/ApImageService.js'; +import { ApMfmService } from '@/core/activitypub/ApMfmService.js'; +import { MfmService } from '@/core/MfmService.js'; +import { HashtagService } from '@/core/HashtagService.js'; +import UsersChart from '@/core/chart/charts/users.js'; +import { ChartLoggerService } from '@/core/chart/ChartLoggerService.js'; +import InstanceChart from '@/core/chart/charts/instance.js'; +import { ApLoggerService } from '@/core/activitypub/ApLoggerService.js'; +import { AccountMoveService } from '@/core/AccountMoveService.js'; +import { ReactionService } from '@/core/ReactionService.js'; +import { NotificationService } from '@/core/NotificationService.js'; + +process.env.NODE_ENV = 'test'; + +describe('UserEntityService', () => { + describe('pack/packMany', () => { + let app: TestingModule; + let service: UserEntityService; + let usersRepository: UsersRepository; + let userProfileRepository: UserProfilesRepository; + let userMemosRepository: UserMemoRepository; + let followingRepository: FollowingsRepository; + let followingRequestRepository: FollowRequestsRepository; + let blockingRepository: BlockingsRepository; + let mutingRepository: MutingsRepository; + let renoteMutingsRepository: RenoteMutingsRepository; + + async function createUser(userData: Partial = {}, profileData: Partial = {}) { + const un = secureRndstr(16); + const user = await usersRepository + .insert({ + ...userData, + id: genAidx(Date.now()), + username: un, + usernameLower: un, + }) + .then(x => usersRepository.findOneByOrFail(x.identifiers[0])); + + await userProfileRepository.insert({ + ...profileData, + userId: user.id, + }); + + return user; + } + + async function memo(writer: MiUser, target: MiUser, memo: string) { + await userMemosRepository.insert({ + id: genAidx(Date.now()), + userId: writer.id, + targetUserId: target.id, + memo, + }); + } + + async function follow(follower: MiUser, followee: MiUser) { + await followingRepository.insert({ + id: genAidx(Date.now()), + followerId: follower.id, + followeeId: followee.id, + }); + } + + async function requestFollow(requester: MiUser, requestee: MiUser) { + await followingRequestRepository.insert({ + id: genAidx(Date.now()), + followerId: requester.id, + followeeId: requestee.id, + }); + } + + async function block(blocker: MiUser, blockee: MiUser) { + await blockingRepository.insert({ + id: genAidx(Date.now()), + blockerId: blocker.id, + blockeeId: blockee.id, + }); + } + + async function mute(mutant: MiUser, mutee: MiUser) { + await mutingRepository.insert({ + id: genAidx(Date.now()), + muterId: mutant.id, + muteeId: mutee.id, + }); + } + + async function muteRenote(mutant: MiUser, mutee: MiUser) { + await renoteMutingsRepository.insert({ + id: genAidx(Date.now()), + muterId: mutant.id, + muteeId: mutee.id, + }); + } + + function randomIntRange(weight = 10) { + return [...Array(Math.floor(Math.random() * weight))].map((it, idx) => idx); + } + + beforeAll(async () => { + const services = [ + UserEntityService, + ApPersonService, + NoteEntityService, + PageEntityService, + CustomEmojiService, + AnnouncementService, + RoleService, + FederatedInstanceService, + IdService, + AvatarDecorationService, + UtilityService, + EmojiEntityService, + ModerationLogService, + GlobalEventService, + DriveFileEntityService, + MetaService, + FetchInstanceMetadataService, + CacheService, + ApResolverService, + ApNoteService, + ApImageService, + ApMfmService, + MfmService, + HashtagService, + UsersChart, + ChartLoggerService, + InstanceChart, + ApLoggerService, + AccountMoveService, + ReactionService, + NotificationService, + ]; + + app = await Test.createTestingModule({ + imports: [GlobalModule, CoreModule], + providers: [ + ...services, + ...services.map(x => ({ provide: x.name, useExisting: x })), + ], + }).compile(); + await app.init(); + app.enableShutdownHooks(); + + service = app.get(UserEntityService); + usersRepository = app.get(DI.usersRepository); + userProfileRepository = app.get(DI.userProfilesRepository); + userMemosRepository = app.get(DI.userMemosRepository); + followingRepository = app.get(DI.followingsRepository); + followingRequestRepository = app.get(DI.followRequestsRepository); + blockingRepository = app.get(DI.blockingsRepository); + mutingRepository = app.get(DI.mutingsRepository); + renoteMutingsRepository = app.get(DI.renoteMutingsRepository); + }); + + afterAll(async () => { + await app.close(); + }); + + test('UserLite', async() => { + const me = await createUser(); + const who = await createUser(); + + await memo(me, who, 'memo'); + + const actual = await service.pack(who, me, { schema: 'UserLite' }) as any; + // no detail + expect(actual.memo).toBeUndefined(); + // no detail and me + expect(actual.birthday).toBeUndefined(); + // no detail and me + expect(actual.achievements).toBeUndefined(); + }); + + test('UserDetailedNotMe', async() => { + const me = await createUser(); + const who = await createUser({}, { birthday: '2000-01-01' }); + + await memo(me, who, 'memo'); + + const actual = await service.pack(who, me, { schema: 'UserDetailedNotMe' }) as any; + // is detail + expect(actual.memo).toBe('memo'); + // is detail + expect(actual.birthday).toBe('2000-01-01'); + // no detail and me + expect(actual.achievements).toBeUndefined(); + }); + + test('MeDetailed', async() => { + const achievements = [{ name: 'achievement', unlockedAt: new Date().getTime() }]; + const me = await createUser({}, { + birthday: '2000-01-01', + achievements: achievements, + }); + await memo(me, me, 'memo'); + + const actual = await service.pack(me, me, { schema: 'MeDetailed' }) as any; + // is detail + expect(actual.memo).toBe('memo'); + // is detail + expect(actual.birthday).toBe('2000-01-01'); + // is detail and me + expect(actual.achievements).toEqual(achievements); + }); + + describe('packManyによるpreloadがある時、preloadが無い時とpackの結果が同じになるか見たい', () => { + test('no-preload', async() => { + const me = await createUser(); + // meがフォローしてる人たち + const followeeMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of followeeMe) { + await follow(me, who); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(true); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meをフォローしてる人たち + const followerMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of followerMe) { + await follow(who, me); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(true); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meがフォローリクエストを送った人たち + const requestsFromYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of requestsFromYou) { + await requestFollow(me, who); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(true); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meにフォローリクエストを送った人たち + const requestsToYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of requestsToYou) { + await requestFollow(who, me); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(true); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meがブロックしてる人たち + const blockingYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of blockingYou) { + await block(me, who); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(true); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meをブロックしてる人たち + const blockingMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of blockingMe) { + await block(who, me); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(true); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + + // meがミュートしてる人たち + const muters = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of muters) { + await mute(me, who); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(true); + expect(actual.isRenoteMuted).toBe(false); + } + + // meがリノートミュートしてる人たち + const renoteMuters = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of renoteMuters) { + await muteRenote(me, who); + const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any; + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(true); + } + }); + + test('preload', async() => { + const me = await createUser(); + + { + // meがフォローしてる人たち + const followeeMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of followeeMe) { + await follow(me, who); + } + const actualList = await service.packMany(followeeMe, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(true); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meをフォローしてる人たち + const followerMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of followerMe) { + await follow(who, me); + } + const actualList = await service.packMany(followerMe, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(true); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meがフォローリクエストを送った人たち + const requestsFromYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of requestsFromYou) { + await requestFollow(me, who); + } + const actualList = await service.packMany(requestsFromYou, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(true); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meにフォローリクエストを送った人たち + const requestsToYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of requestsToYou) { + await requestFollow(who, me); + } + const actualList = await service.packMany(requestsToYou, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(true); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meがブロックしてる人たち + const blockingYou = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of blockingYou) { + await block(me, who); + } + const actualList = await service.packMany(blockingYou, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(true); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meをブロックしてる人たち + const blockingMe = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of blockingMe) { + await block(who, me); + } + const actualList = await service.packMany(blockingMe, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(true); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meがミュートしてる人たち + const muters = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of muters) { + await mute(me, who); + } + const actualList = await service.packMany(muters, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(true); + expect(actual.isRenoteMuted).toBe(false); + } + } + + { + // meがリノートミュートしてる人たち + const renoteMuters = await Promise.all(randomIntRange().map(() => createUser())); + for (const who of renoteMuters) { + await muteRenote(me, who); + } + const actualList = await service.packMany(renoteMuters, me, { schema: 'UserDetailed' }) as any; + for (const actual of actualList) { + expect(actual.isFollowing).toBe(false); + expect(actual.isFollowed).toBe(false); + expect(actual.hasPendingFollowRequestFromYou).toBe(false); + expect(actual.hasPendingFollowRequestToYou).toBe(false); + expect(actual.isBlocking).toBe(false); + expect(actual.isBlocked).toBe(false); + expect(actual.isMuted).toBe(false); + expect(actual.isRenoteMuted).toBe(true); + } + } + }); + }); + }); +}); diff --git a/packages/backend/test/unit/misc/check-against-url.ts b/packages/backend/test/unit/misc/check-against-url.ts index 1cc12cbea2..88edaed839 100644 --- a/packages/backend/test/unit/misc/check-against-url.ts +++ b/packages/backend/test/unit/misc/check-against-url.ts @@ -14,38 +14,38 @@ function assertOne(activity: IObject) { describe('assertActivityMatchesUrls', () => { test('id', () => { - expect(assertOne({ id: 'bad' })).toThrow(/bad Activity/); - expect(assertOne({ id: 'good' })).not.toThrow(); + expect(assertOne({ type: 'Test', id: 'bad' })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', id: 'good' })).not.toThrow(); }); test('simple url', () => { - expect(assertOne({ url: 'bad' })).toThrow(/bad Activity/); - expect(assertOne({ url: 'good' })).not.toThrow(); + expect(assertOne({ type: 'Test', url: 'bad' })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: 'good' })).not.toThrow(); }); test('array of urls', () => { - expect(assertOne({ url: ['bad'] })).toThrow(/bad Activity/); - expect(assertOne({ url: ['bad', 'other'] })).toThrow(/bad Activity/); - expect(assertOne({ url: ['good'] })).not.toThrow(); - expect(assertOne({ url: ['bad', 'good'] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: ['bad'] })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: ['bad', 'other'] })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: ['good'] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: ['bad', 'good'] })).not.toThrow(); }); test('array of objects', () => { - expect(assertOne({ url: [{ href: 'bad' }] })).toThrow(/bad Activity/); - expect(assertOne({ url: [{ href: 'bad' }, { href: 'other' }] })).toThrow(/bad Activity/); - expect(assertOne({ url: [{ href: 'good' }] })).not.toThrow(); - expect(assertOne({ url: [{ href: 'bad' }, { href: 'good' }] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'bad' }] })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'bad' }, { type: 'Test', href: 'other' }] })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'good' }] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'bad' }, { type: 'Test', href: 'good' }] })).not.toThrow(); }); test('mixed array', () => { - expect(assertOne({ url: [{ href: 'bad' }, 'other'] })).toThrow(/bad Activity/); - expect(assertOne({ url: [{ href: 'bad' }, 'good'] })).not.toThrow(); - expect(assertOne({ url: ['bad', { href: 'good' }] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'bad' }, 'other'] })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', url: [{ type: 'Test', href: 'bad' }, 'good'] })).not.toThrow(); + expect(assertOne({ type: 'Test', url: ['bad', { type: 'Test', href: 'good' }] })).not.toThrow(); }); test('id and url', () => { - expect(assertOne({ id: 'other', url: 'bad' })).toThrow(/bad Activity/); - expect(assertOne({ id: 'bad', url: 'good' })).not.toThrow(); - expect(assertOne({ id: 'good', url: 'bad' })).not.toThrow(); + expect(assertOne({ type: 'Test', id: 'other', url: 'bad' })).toThrow(/bad Activity/); + expect(assertOne({ type: 'Test', id: 'bad', url: 'good' })).not.toThrow(); + expect(assertOne({ type: 'Test', id: 'good', url: 'bad' })).not.toThrow(); }); }); diff --git a/packages/backend/test/unit/misc/is-renote.ts b/packages/backend/test/unit/misc/is-renote.ts new file mode 100644 index 0000000000..080271e404 --- /dev/null +++ b/packages/backend/test/unit/misc/is-renote.ts @@ -0,0 +1,89 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { isQuote, isRenote } from '@/misc/is-renote.js'; +import { MiNote } from '@/models/Note.js'; + +const base: MiNote = { + id: 'some-note-id', + updatedAt: null, + replyId: null, + reply: null, + renoteId: null, + renote: null, + threadId: null, + text: null, + name: null, + cw: null, + userId: 'some-user-id', + user: null, + localOnly: false, + reactionAcceptance: null, + renoteCount: 0, + repliesCount: 0, + clippedCount: 0, + reactions: {}, + visibility: 'public', + uri: null, + url: null, + fileIds: [], + attachedFileTypes: [], + visibleUserIds: [], + mentions: [], + mentionedRemoteUsers: '', + reactionAndUserPairCache: [], + emojis: [], + tags: [], + hasPoll: false, + channelId: null, + channel: null, + userHost: null, + replyUserId: null, + replyUserHost: null, + renoteUserId: null, + renoteUserHost: null, +}; + +describe('misc:is-renote', () => { + test('note without renoteId should not be Renote', () => { + expect(isRenote(base)).toBe(false); + }); + + test('note with renoteId should be Renote and not be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id' }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(false); + }); + + test('note with renoteId and text should be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id', text: 'some-text' }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(true); + }); + + test('note with renoteId and cw should be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id', cw: 'some-cw' }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(true); + }); + + test('note with renoteId and replyId should be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id', replyId: 'some-reply-id' }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(true); + }); + + test('note with renoteId and poll should be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id', hasPoll: true }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(true); + }); + + test('note with renoteId and non-empty fileIds should be Quote', () => { + const note: MiNote = { ...base, renoteId: 'some-renote-id', fileIds: ['some-file-id'] }; + expect(isRenote(note)).toBe(true); + expect(isQuote(note as any)).toBe(true); + }); +}); diff --git a/packages/backend/test/unit/misc/loader.ts b/packages/backend/test/unit/misc/loader.ts index fa37950951..2cf54e1555 100644 --- a/packages/backend/test/unit/misc/loader.ts +++ b/packages/backend/test/unit/misc/loader.ts @@ -1,3 +1,8 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + import { DebounceLoader } from '@/misc/loader.js'; class Mock { diff --git a/packages/backend/test/utils.ts b/packages/backend/test/utils.ts index cd5dddd68d..86814fffe0 100644 --- a/packages/backend/test/utils.ts +++ b/packages/backend/test/utils.ts @@ -9,11 +9,10 @@ import { basename, isAbsolute } from 'node:path'; import { randomUUID } from 'node:crypto'; import { inspect } from 'node:util'; import WebSocket, { ClientOptions } from 'ws'; -import fetch, { File, RequestInit } from 'node-fetch'; +import fetch, { File, RequestInit, type Headers } from 'node-fetch'; import { DataSource } from 'typeorm'; import { JSDOM } from 'jsdom'; import { DEFAULT_POLICIES } from '@/core/RoleService.js'; -import { Packed } from '@/misc/json-schema.js'; import { validateContentTypeSetAsActivityPub } from '@/core/activitypub/misc/validator.js'; import { entities } from '../src/postgres.js'; import { loadConfig } from '../src/config.js'; @@ -21,7 +20,7 @@ import type * as misskey from 'misskey-js'; export { server as startServer, jobQueue as startJobQueue } from '@/boot/common.js'; -interface UserToken { +export interface UserToken { token: string; bearer?: boolean; } @@ -35,20 +34,15 @@ export const cookie = (me: UserToken): string => { return `token=${me.token};`; }; -export const api = async (endpoint: string, params: any, me?: UserToken) => { - const normalized = endpoint.replace(/^\//, ''); - return await request(`api/${normalized}`, params, me); -}; - -export type ApiRequest = { - endpoint: string, - parameters: object, +export type ApiRequest = { + endpoint: E, + parameters: P, user: UserToken | undefined, }; -export const successfulApiCall = async (request: ApiRequest, assertion: { +export const successfulApiCall = async (request: ApiRequest, assertion: { status?: number, -} = {}): Promise => { +} = {}): Promise> => { const { endpoint, parameters, user } = request; const res = await api(endpoint, parameters, user); const status = assertion.status ?? (res.body == null ? 204 : 200); @@ -56,7 +50,7 @@ export const successfulApiCall = async (request: ApiRequest, assertion: { return res.body; }; -export const failedApiCall = async (request: ApiRequest, assertion: { +export const failedApiCall = async (request: ApiRequest, assertion: { status: number, code: string, id: string @@ -70,7 +64,7 @@ export const failedApiCall = async (request: ApiRequest, assertion: { return res.body; }; -const request = async (path: string, params: any, me?: UserToken): Promise<{ +export const api = async (path: E, params: misskey.Endpoints[E]['req'], me?: UserToken): Promise<{ status: number, headers: Headers, body: any @@ -86,7 +80,7 @@ const request = async (path: string, params: any, me?: UserToken): Promise<{ bodyAuth.i = me.token; } - const res = await relativeFetch(path, { + const res = await relativeFetch(`api/${path}`, { method: 'POST', headers, body: JSON.stringify(Object.assign(bodyAuth, params)), @@ -141,7 +135,7 @@ export const signup = async (params?: Partial => { +export const post = async (user: UserToken, params: misskey.Endpoints['notes/create']['req']): Promise => { const q = params; const res = await api('notes/create', q, user); @@ -159,8 +153,8 @@ export const createAppToken = async (user: UserToken, permissions: (typeof missk }; // 非公開ノートをAPI越しに見たときのノート NoteEntityService.ts -export const hiddenNote = (note: any): any => { - const temp = { +export const hiddenNote = (note: misskey.entities.Note): misskey.entities.Note => { + const temp: misskey.entities.Note = { ...note, fileIds: [], files: [], @@ -173,21 +167,22 @@ export const hiddenNote = (note: any): any => { return temp; }; -export const react = async (user: UserToken, note: any, reaction: string): Promise => { +export const react = async (user: UserToken, note: misskey.entities.Note, reaction: string): Promise => { await api('notes/reactions/create', { noteId: note.id, reaction: reaction, }, user); }; -export const userList = async (user: UserToken, userList: any = {}): Promise => { +export const userList = async (user: UserToken, userList: Partial = {}): Promise => { const res = await api('users/lists/create', { name: 'test', + ...userList, }, user); return res.body; }; -export const page = async (user: UserToken, page: any = {}): Promise => { +export const page = async (user: UserToken, page: Partial = {}): Promise => { const res = await api('pages/create', { alignCenter: false, content: [ @@ -198,7 +193,7 @@ export const page = async (user: UserToken, page: any = {}): Promise => { }, ], eyeCatchingImageId: null, - font: 'sans-serif', + font: 'sans-serif' as any, hideTitleWhenPinned: false, name: '1678594845072', script: '', @@ -210,7 +205,7 @@ export const page = async (user: UserToken, page: any = {}): Promise => { return res.body; }; -export const play = async (user: UserToken, play: any = {}): Promise => { +export const play = async (user: UserToken, play: Partial = {}): Promise => { const res = await api('flash/create', { permissions: [], script: 'test', @@ -221,7 +216,7 @@ export const play = async (user: UserToken, play: any = {}): Promise => { return res.body; }; -export const clip = async (user: UserToken, clip: any = {}): Promise => { +export const clip = async (user: UserToken, clip: Partial = {}): Promise => { const res = await api('clips/create', { description: null, isPublic: true, @@ -231,18 +226,18 @@ export const clip = async (user: UserToken, clip: any = {}): Promise => { return res.body; }; -export const galleryPost = async (user: UserToken, channel: any = {}): Promise => { +export const galleryPost = async (user: UserToken, galleryPost: Partial = {}): Promise => { const res = await api('gallery/posts/create', { description: null, fileIds: [], isSensitive: false, title: 'test', - ...channel, + ...galleryPost, }, user); return res.body; }; -export const channel = async (user: UserToken, channel: any = {}): Promise => { +export const channel = async (user: UserToken, channel: Partial = {}): Promise => { const res = await api('channels/create', { bannerId: null, description: null, @@ -252,7 +247,7 @@ export const channel = async (user: UserToken, channel: any = {}): Promise return res.body; }; -export const role = async (user: UserToken, role: any = {}, policies: any = {}): Promise => { +export const role = async (user: UserToken, role: Partial = {}, policies: any = {}): Promise => { const res = await api('admin/roles/create', { asBadge: false, canEditMembersByModerator: false, @@ -260,7 +255,7 @@ export const role = async (user: UserToken, role: any = {}, policies: any = {}): condFormula: { id: 'ebef1684-672d-49b6-ad82-1b3ec3784f85', type: 'isRemote', - }, + } as any, description: '', displayOrder: 0, iconUrl: null, @@ -298,7 +293,7 @@ interface UploadOptions { export const uploadFile = async (user?: UserToken, { path, name, blob }: UploadOptions = {}): Promise<{ status: number, headers: Headers, - body: misskey.Endpoints['drive/files/create']['res'] | null + body: misskey.entities.DriveFile | null }> => { const absPath = path == null ? new URL('resources/Lenna.jpg', import.meta.url) @@ -335,14 +330,14 @@ export const uploadFile = async (user?: UserToken, { path, name, blob }: UploadO }; }; -export const uploadUrl = async (user: UserToken, url: string): Promise> => { +export const uploadUrl = async (user: UserToken, url: string): Promise => { const marker = Math.random().toString(); const catcher = makeStreamCatcher( user, 'main', (msg) => msg.type === 'urlUploadFinished' && msg.body.marker === marker, - (msg) => msg.body.file as Packed<'DriveFile'>, + (msg) => msg.body.file, 60 * 1000, ); diff --git a/packages/frontend/.storybook/fakes.ts b/packages/frontend/.storybook/fakes.ts index de28d343d1..a2325e69c6 100644 --- a/packages/frontend/.storybook/fakes.ts +++ b/packages/frontend/.storybook/fakes.ts @@ -27,7 +27,7 @@ export function galleryPost(isSensitive = false) { id: 'somepostid', createdAt: '2016-12-28T22:49:51.000Z', updatedAt: '2016-12-28T22:49:51.000Z', - userid: 'someuserid', + userId: 'someuserid', user: userDetailed(), title: 'Some post title', description: 'Some post description', @@ -75,9 +75,8 @@ export function userDetailed(id = 'someuserid', username = 'miskist', host = 'mi avatarUrl: 'https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/about-icon.png?raw=true', avatarBlurhash: 'eQFRshof5NWBRi},juayfPju53WB?0ofs;s*a{ofjuay^SoMEJR%ay', avatarDecorations: [], - emojis: [], + emojis: {}, bannerBlurhash: 'eQA^IW^-MH8w9tE8I=S^o{$*R4RikXtSxutRozjEnNR.RQadoyozog', - bannerColor: '#000000', bannerUrl: 'https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/fedi.jpg?raw=true', birthday: '2014-06-20', createdAt: '2016-12-28T22:49:51.000Z', @@ -119,11 +118,16 @@ export function userDetailed(id = 'someuserid', username = 'miskist', host = 'mi publicReactions: false, securityKeys: false, twoFactorEnabled: false, + usePasswordLessLogin: false, twoFactorBackupCodesStock: 'none', updatedAt: null, + lastFetchedAt: null, uri: null, url: null, + movedTo: null, + alsoKnownAs: null, notify: 'none', + memo: null }; } diff --git a/packages/frontend/.storybook/generate.tsx b/packages/frontend/.storybook/generate.tsx index 1e925aede6..d74c83a500 100644 --- a/packages/frontend/.storybook/generate.tsx +++ b/packages/frontend/.storybook/generate.tsx @@ -82,23 +82,16 @@ function h( return Object.assign(props || {}, { type }) as T; } -declare global { - namespace JSX { - type Element = estree.Node; - type ElementClass = never; - type ElementAttributesProperty = never; - type ElementChildrenAttribute = never; - type IntrinsicAttributes = never; - type IntrinsicClassAttributes = never; - type IntrinsicElements = { - [T in keyof typeof generator as ToKebab>>]: { - [K in keyof Omit< - Parameters<(typeof generator)[T]>[0], - 'type' - >]?: Parameters<(typeof generator)[T]>[0][K]; - }; +declare namespace h.JSX { + type Element = estree.Node; + type IntrinsicElements = { + [T in keyof typeof generator as ToKebab>>]: { + [K in keyof Omit< + Parameters<(typeof generator)[T]>[0], + 'type' + >]?: Parameters<(typeof generator)[T]>[0][K]; }; - } + }; } function toStories(component: string): Promise { @@ -388,6 +381,7 @@ function toStories(component: string): Promise { '/* eslint-disable @typescript-eslint/explicit-function-return-type */\n' + '/* eslint-disable import/no-default-export */\n' + '/* eslint-disable import/no-duplicates */\n' + + '/* eslint-disable import/order */\n' + generate(program, { generator }) + (hasImplStories ? readFileSync(`${implStories}.ts`, 'utf-8') : ''), { diff --git a/packages/frontend/.storybook/main.ts b/packages/frontend/.storybook/main.ts index 0a87488573..d3822942cd 100644 --- a/packages/frontend/.storybook/main.ts +++ b/packages/frontend/.storybook/main.ts @@ -34,7 +34,7 @@ const config = { disableTelemetry: true, }, async viteFinal(config) { - const replacePluginForIsChromatic = config.plugins?.findIndex((plugin) => plugin && (plugin as Partial)?.name === 'replace') ?? -1; + const replacePluginForIsChromatic = config.plugins?.findIndex((plugin: Plugin) => plugin && plugin.name === 'replace') ?? -1; if (~replacePluginForIsChromatic) { config.plugins?.splice(replacePluginForIsChromatic, 1); } diff --git a/packages/frontend/.storybook/mocks.ts b/packages/frontend/.storybook/mocks.ts index 817b0125e7..29cb112ccb 100644 --- a/packages/frontend/.storybook/mocks.ts +++ b/packages/frontend/.storybook/mocks.ts @@ -6,7 +6,8 @@ import { type SharedOptions, http, HttpResponse } from 'msw'; export const onUnhandledRequest = ((req, print) => { - if (req.url.hostname !== 'localhost' || /^\/(?:client-assets\/|fluent-emojis?\/|iframe.html$|node_modules\/|src\/|sb-|static-assets\/|vite\/)/.test(req.url.pathname)) { + const url = new URL(req.url); + if (url.hostname !== 'localhost' || /^\/(?:client-assets\/|fluent-emojis?\/|iframe.html$|node_modules\/|src\/|sb-|static-assets\/|vite\/)/.test(url.pathname)) { return } print.warning() diff --git a/packages/frontend/.storybook/preview-head.html b/packages/frontend/.storybook/preview-head.html index 30f3ebfb64..ae42fd49bc 100644 --- a/packages/frontend/.storybook/preview-head.html +++ b/packages/frontend/.storybook/preview-head.html @@ -1,6 +1,11 @@ + + - + diff --git a/packages/frontend/src/components/MkFormDialog.vue b/packages/frontend/src/components/MkFormDialog.vue index deedc5badb..124f114111 100644 --- a/packages/frontend/src/components/MkFormDialog.vue +++ b/packages/frontend/src/components/MkFormDialog.vue @@ -21,8 +21,9 @@ SPDX-License-Identifier: AGPL-3.0-only
-