diff --git a/.config/example.yml b/.config/example.yml index 2d1e82ee0b..c7884a3687 100644 --- a/.config/example.yml +++ b/.config/example.yml @@ -107,23 +107,51 @@ port: 3000 # Proxy trust settings # -# Changes how the server interpret the origin IP of the request. +# Specifies the IP addresses that Misskey will use as trusted +# reverse proxies (e.g., nginx, Cloudflare). This affects how +# Misskey determines the source IP for each request and is used +# for important rate limiting and security features. If the value +# is not set correctly, Misskey may use the IP address of the +# reverse proxy instead of the actual source IP, which may lead to +# unintended rate limiting or security vulnerabilities. +# By default, the loopback network and private network address +# ranges shown below are trusted. +# If you are using a single reverse proxy and it is on the same +# machine or the same private network as Misskey, it is unlikely you +# need to change this setting, and the default setting is fine. +# Also, if you are using multiple reverse proxy servers and they are +# all on the same private network as Misskey, the default setting +# is fine. +# However, if you are using a reverse proxy server that accesses +# Misskey web servers and streaming servers via public IP addresses +# (for example, Cloudflare), you must set this variable. +# When changing this setting, you can use one of the following values: # -# Any format supported by Fastify is accepted. -# Default: trust all proxies (i.e. trustProxy: true) -# See: https://fastify.dev/docs/latest/reference/server/#trustproxy -# To improve security, we recommend that you configure your settings appropriately. -# Incorrect configuration can cause issues such as difficulty signing in, -# so please configure your settings carefully. +# - true: Trust all proxies +# - false: Do not trust any proxies +# - IP address, IP address range, or array of them: Trust hops that +# match the specified criteria. +# - Integer: Trust the nth hop from the front-facing proxy server as +# the client. +# For more information on how to configure this setting, please refer +# to the Fastify documentation: +# https://fastify.dev/docs/latest/Reference/Server/#trustproxy # -#trustProxy: [ -# '10.0.0.0/8' -# '172.16.0.0/12' -# '192.168.0.0/16' -# '127.0.0.1/32' -# '::1/128' -# 'fc00::/7' -#] +# Note that if this variable is set, it overrides the default range, +# so if you have both an external reverse proxy and a proxy on the +# local host, you must include both IPs (or IP ranges). +# +#trustProxy: +# - '10.0.0.0/8' +# - '172.16.0.0/12' +# - '192.168.0.0/16' +# - '127.0.0.1/32' +# - '::1/128' +# - 'fc00::/7' +# # Example: If you are using some external reverse proxies like CDNs, +# # you may need to add the CDN IP ranges here. +# # If you're using Cloudflare, you can find IP Ranges at: +# # https://www.cloudflare.com/ips/ # ┌──────────────────────────┐ #───┘ PostgreSQL configuration └──────────────────────────────── @@ -293,6 +321,10 @@ id: 'aidx' # Whether disable HSTS #disableHsts: true +# Enable internal IP-based rate limiting (default: true) +# To configure them in reverse proxy instead, set this to false. +#enableIpRateLimit: true + # Number of worker processes #clusterLimit: 1 diff --git a/.dockerignore b/.dockerignore index f204349160..39cbe2726f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,6 +6,7 @@ Dockerfile build/ built/ +src-js/ db/ .devcontainer/compose.yml node_modules/ diff --git a/.github/ISSUE_TEMPLATE/01_bug-report.yml b/.github/ISSUE_TEMPLATE/01_bug-report.yml index fd68e602dd..00da7e9a2a 100644 --- a/.github/ISSUE_TEMPLATE/01_bug-report.yml +++ b/.github/ISSUE_TEMPLATE/01_bug-report.yml @@ -54,7 +54,7 @@ body: * Model and OS of the device(s): MacBook Pro (14inch, 2021), macOS Ventura 13.4 * Browser: Chrome 113.0.5672.126 * Server URL: misskey.example.com - * Misskey: 2025.x.x + * Misskey: 2026.x.x value: | * Model and OS of the device(s): * Browser: @@ -74,7 +74,7 @@ body: Examples: * Installation Method or Hosting Service: docker compose, k8s/docker, systemd, "Misskey install shell script", development environment - * Misskey: 2025.x.x + * Misskey: 2026.x.x * Node: 20.x.x * PostgreSQL: 18.x.x * Redis: 7.x.x diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000..7c30489afe --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,3 @@ +# Copilot Instructions for Misskey + +- en-US.yml を編集しないでください。 diff --git a/.github/workflows/api-misskey-js.yml b/.github/workflows/api-misskey-js.yml index 49ca3058f3..1a35b86041 100644 --- a/.github/workflows/api-misskey-js.yml +++ b/.github/workflows/api-misskey-js.yml @@ -16,13 +16,13 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/changelog-check.yml b/.github/workflows/changelog-check.yml index d17999a271..37664e950e 100644 --- a/.github/workflows/changelog-check.yml +++ b/.github/workflows/changelog-check.yml @@ -12,9 +12,9 @@ jobs: steps: - name: Checkout head - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Setup Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' diff --git a/.github/workflows/check-misskey-js-autogen.yml b/.github/workflows/check-misskey-js-autogen.yml index 8a81e85521..a31a4d85fa 100644 --- a/.github/workflows/check-misskey-js-autogen.yml +++ b/.github/workflows/check-misskey-js-autogen.yml @@ -18,7 +18,7 @@ jobs: if: ${{ github.event.pull_request.mergeable == null || github.event.pull_request.mergeable == true }} steps: - name: checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 with: submodules: true persist-credentials: false @@ -29,7 +29,7 @@ jobs: - name: setup node id: setup-node - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: pnpm @@ -66,7 +66,7 @@ jobs: if: ${{ github.event.pull_request.mergeable == null || github.event.pull_request.mergeable == true }} steps: - name: checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 with: submodules: true persist-credentials: false diff --git a/.github/workflows/check-misskey-js-version.yml b/.github/workflows/check-misskey-js-version.yml index ad07d47b65..f6095110c9 100644 --- a/.github/workflows/check-misskey-js-version.yml +++ b/.github/workflows/check-misskey-js-version.yml @@ -20,7 +20,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Check version run: | if [ "$(jq -r '.version' package.json)" != "$(jq -r '.version' packages/misskey-js/package.json)" ]; then diff --git a/.github/workflows/check-spdx-license-id.yml b/.github/workflows/check-spdx-license-id.yml index fe71473ea3..d1448fc5d0 100644 --- a/.github/workflows/check-spdx-license-id.yml +++ b/.github/workflows/check-spdx-license-id.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Check run: | counter=0 diff --git a/.github/workflows/check_copyright_year.yml b/.github/workflows/check_copyright_year.yml index 40016d39c5..7514358929 100644 --- a/.github/workflows/check_copyright_year.yml +++ b/.github/workflows/check_copyright_year.yml @@ -10,7 +10,7 @@ jobs: check_copyright_year: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 - run: | if [ "$(grep Copyright COPYING | sed -e 's/.*2014-\([0-9]*\) .*/\1/g')" -ne "$(date +%Y)" ]; then echo "Please change copyright year!" diff --git a/.github/workflows/deploy-test-environment.yml b/.github/workflows/deploy-test-environment.yml index 32c7c6b6ea..77464b6465 100644 --- a/.github/workflows/deploy-test-environment.yml +++ b/.github/workflows/deploy-test-environment.yml @@ -28,7 +28,7 @@ jobs: wait_time: ${{ steps.get-wait-time.outputs.wait_time }} steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Check allowed users id: check-allowed-users diff --git a/.github/workflows/docker-develop.yml b/.github/workflows/docker-develop.yml index 8a97959907..bedd501bc9 100644 --- a/.github/workflows/docker-develop.yml +++ b/.github/workflows/docker-develop.yml @@ -27,7 +27,7 @@ jobs: platform=${{ matrix.platform }} echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV - name: Check out the repo - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to Docker Hub diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 37f6aca588..fec5d1d530 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -32,7 +32,7 @@ jobs: platform=${{ matrix.platform }} echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV - name: Check out the repo - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Docker meta diff --git a/.github/workflows/dockle.yml b/.github/workflows/dockle.yml index 45b8d23dda..916b905fd0 100644 --- a/.github/workflows/dockle.yml +++ b/.github/workflows/dockle.yml @@ -11,38 +11,43 @@ on: jobs: dockle: runs-on: ubuntu-latest + env: DOCKER_CONTENT_TRUST: 1 DOCKLE_VERSION: 0.4.15 steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 - name: Download and install dockle v${{ env.DOCKLE_VERSION }} run: | + set -eux curl -L -o dockle.deb "https://github.com/goodwithtech/dockle/releases/download/v${DOCKLE_VERSION}/dockle_${DOCKLE_VERSION}_Linux-64bit.deb" sudo dpkg -i dockle.deb - - run: | - cp .config/docker_example.env .config/docker.env - cp ./compose_example.yml ./compose.yml - - - run: | - docker compose up -d web - IMAGE_ID=$(docker compose images --format json web | jq -r '.[0].ID') - docker tag "${IMAGE_ID}" misskey-web:latest - - - name: Prune docker junk (optional but recommended) + - name: Build web image (docker build) run: | - docker system prune -af - docker volume prune -f + set -eux + docker build -t "misskey-web:ci" . + docker image ls - - name: Save image for Dockle + - name: Mount tmpfs for Dockle tar + env: + TMPFS_SIZE: 8G run: | - docker save misskey-web:latest -o ./misskey-web.tar - ls -lh ./misskey-web.tar + set -eux + sudo mkdir -p /mnt/dockle-tmp + sudo mount -t tmpfs -o size=${{ env.TMPFS_SIZE }} tmpfs /mnt/dockle-tmp + free -h + df -h - - name: Run Dockle with tar input + - name: Save image tar into tmpfs run: | - dockle --exit-code 1 --input ./misskey-web.tar + set -eux + docker save misskey-web:ci -o /mnt/dockle-tmp/misskey-web.tar + ls -lh /mnt/dockle-tmp/misskey-web.tar + - name: Run Dockle Scan (tar input) + run: | + set -eux + dockle --exit-code 1 --input /mnt/dockle-tmp/misskey-web.tar diff --git a/.github/workflows/get-api-diff.yml b/.github/workflows/get-api-diff.yml index f8a0c4aaa4..c7ab3e2a29 100644 --- a/.github/workflows/get-api-diff.yml +++ b/.github/workflows/get-api-diff.yml @@ -25,14 +25,14 @@ jobs: ref: refs/pull/${{ github.event.number }}/merge steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: ref: ${{ matrix.ref }} submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/get-backend-memory.yml b/.github/workflows/get-backend-memory.yml index 99f89631bb..0dcaaa8cb3 100644 --- a/.github/workflows/get-backend-memory.yml +++ b/.github/workflows/get-backend-memory.yml @@ -40,14 +40,14 @@ jobs: - 56312:6379 steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: ref: ${{ matrix.ref }} submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 91cbe52c38..0d9ac81314 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -36,13 +36,13 @@ jobs: pnpm_install: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: fetch-depth: 0 submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 - - uses: actions/setup-node@v6.1.0 + uses: pnpm/action-setup@v4.4.0 + - uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' @@ -69,13 +69,13 @@ jobs: eslint-cache-version: v1 eslint-cache-path: ${{ github.workspace }}/node_modules/.cache/eslint-${{ matrix.workspace }} steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: fetch-depth: 0 submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 - - uses: actions/setup-node@v6.1.0 + uses: pnpm/action-setup@v4.4.0 + - uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' @@ -100,13 +100,13 @@ jobs: - sw - misskey-js steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: fetch-depth: 0 submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 - - uses: actions/setup-node@v6.1.0 + uses: pnpm/action-setup@v4.4.0 + - uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/locale.yml b/.github/workflows/locale.yml index 15cc9153f6..a965aae0d1 100644 --- a/.github/workflows/locale.yml +++ b/.github/workflows/locale.yml @@ -16,13 +16,13 @@ jobs: runs-on: ubuntu-latest continue-on-error: true steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: fetch-depth: 0 submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 - - uses: actions/setup-node@v6.1.0 + uses: pnpm/action-setup@v4.4.0 + - uses: actions/setup-node@v6.3.0 with: node-version-file: ".node-version" cache: "pnpm" diff --git a/.github/workflows/on-release-created.yml b/.github/workflows/on-release-created.yml index c9a47385a0..7d19678574 100644 --- a/.github/workflows/on-release-created.yml +++ b/.github/workflows/on-release-created.yml @@ -16,13 +16,13 @@ jobs: id-token: write steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/report-backend-memory.yml b/.github/workflows/report-backend-memory.yml index c339ca49b4..bf2e311c83 100644 --- a/.github/workflows/report-backend-memory.yml +++ b/.github/workflows/report-backend-memory.yml @@ -54,55 +54,110 @@ jobs: BASE_MEMORY=$(cat ./artifacts/memory-base.json) HEAD_MEMORY=$(cat ./artifacts/memory-head.json) - BASE_RSS=$(echo "$BASE_MEMORY" | jq -r '.memory.rss // 0') - HEAD_RSS=$(echo "$HEAD_MEMORY" | jq -r '.memory.rss // 0') + variation() { + calc() { + BASE=$(echo "$BASE_MEMORY" | jq -r ".${1}.${2} // 0") + HEAD=$(echo "$HEAD_MEMORY" | jq -r ".${1}.${2} // 0") - # Calculate difference - if [ "$BASE_RSS" -gt 0 ] && [ "$HEAD_RSS" -gt 0 ]; then - DIFF=$((HEAD_RSS - BASE_RSS)) - DIFF_PERCENT=$(echo "scale=2; ($DIFF * 100) / $BASE_RSS" | bc) + DIFF=$((HEAD - BASE)) + if [ "$BASE" -gt 0 ]; then + DIFF_PERCENT=$(echo "scale=2; ($DIFF * 100) / $BASE" | bc) + else + DIFF_PERCENT=0 + fi - # Convert to MB for readability - BASE_MB=$(echo "scale=2; $BASE_RSS / 1048576" | bc) - HEAD_MB=$(echo "scale=2; $HEAD_RSS / 1048576" | bc) - DIFF_MB=$(echo "scale=2; $DIFF / 1048576" | bc) + # Convert KB to MB for readability + BASE_MB=$(echo "scale=2; $BASE / 1024" | bc) + HEAD_MB=$(echo "scale=2; $HEAD / 1024" | bc) + DIFF_MB=$(echo "scale=2; $DIFF / 1024" | bc) - echo "base_mb=$BASE_MB" >> "$GITHUB_OUTPUT" - echo "head_mb=$HEAD_MB" >> "$GITHUB_OUTPUT" - echo "diff_mb=$DIFF_MB" >> "$GITHUB_OUTPUT" - echo "diff_percent=$DIFF_PERCENT" >> "$GITHUB_OUTPUT" - echo "has_data=true" >> "$GITHUB_OUTPUT" + JSON=$(jq -c -n \ + --argjson base "$BASE_MB" \ + --argjson head "$HEAD_MB" \ + --argjson diff "$DIFF_MB" \ + --argjson diff_percent "$DIFF_PERCENT" \ + '{base: $base, head: $head, diff: $diff, diff_percent: $diff_percent}') - # Determine if this is a significant change (more than 5% increase) - if [ "$(echo "$DIFF_PERCENT > 5" | bc)" -eq 1 ]; then - echo "significant_increase=true" >> "$GITHUB_OUTPUT" - else - echo "significant_increase=false" >> "$GITHUB_OUTPUT" - fi - else - echo "has_data=false" >> "$GITHUB_OUTPUT" - fi + echo "$JSON" + } + + JSON=$(jq -c -n \ + --argjson VmRSS "$(calc $1 VmRSS)" \ + --argjson VmHWM "$(calc $1 VmHWM)" \ + --argjson VmSize "$(calc $1 VmSize)" \ + --argjson VmData "$(calc $1 VmData)" \ + '{VmRSS: $VmRSS, VmHWM: $VmHWM, VmSize: $VmSize, VmData: $VmData}') + + echo "$JSON" + } + + JSON=$(jq -c -n \ + --argjson beforeGc "$(variation beforeGc)" \ + --argjson afterGc "$(variation afterGc)" \ + --argjson afterRequest "$(variation afterRequest)" \ + '{beforeGc: $beforeGc, afterGc: $afterGc, afterRequest: $afterRequest}') + + echo "res=$JSON" >> "$GITHUB_OUTPUT" - id: build-comment name: Build memory comment + env: + RES: ${{ steps.compare.outputs.res }} run: | - HEADER="## Backend Memory Usage Comparison" + HEADER="## Backend memory usage comparison" FOOTER="[See workflow logs for details](https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID})" echo "$HEADER" > ./output.md echo >> ./output.md - if [ "${{ steps.compare.outputs.has_data }}" == "true" ]; then - echo "| Metric | base | head | Diff |" >> ./output.md - echo "|--------|------|------|------|" >> ./output.md - echo "| RSS | ${{ steps.compare.outputs.base_mb }} MB | ${{ steps.compare.outputs.head_mb }} MB | ${{ steps.compare.outputs.diff_mb }} MB (${{ steps.compare.outputs.diff_percent }}%) |" >> ./output.md - echo >> ./output.md + table() { + echo "| Metric | base (MB) | head (MB) | Diff (MB) | Diff (%) |" >> ./output.md + echo "|--------|------:|------:|------:|------:|" >> ./output.md - if [ "${{ steps.compare.outputs.significant_increase }}" == "true" ]; then - echo "⚠️ **Warning**: Memory usage has increased by more than 5%. Please verify this is not an unintended change." >> ./output.md - echo >> ./output.md - fi - else - echo "Could not retrieve memory usage data." >> ./output.md + line() { + METRIC=$2 + BASE=$(echo "$RES" | jq -r ".${1}.${2}.base") + HEAD=$(echo "$RES" | jq -r ".${1}.${2}.head") + DIFF=$(echo "$RES" | jq -r ".${1}.${2}.diff") + DIFF_PERCENT=$(echo "$RES" | jq -r ".${1}.${2}.diff_percent") + + if (( $(echo "$DIFF_PERCENT > 0" | bc -l) )); then + DIFF="+$DIFF" + DIFF_PERCENT="+$DIFF_PERCENT" + fi + + # highlight VmRSS + if [ "$2" = "VmRSS" ]; then + METRIC="**${METRIC}**" + BASE="**${BASE}**" + HEAD="**${HEAD}**" + DIFF="**${DIFF}**" + DIFF_PERCENT="**${DIFF_PERCENT}**" + fi + + echo "| ${METRIC} | ${BASE} MB | ${HEAD} MB | ${DIFF} MB | ${DIFF_PERCENT}% |" >> ./output.md + } + + line $1 VmRSS + line $1 VmHWM + line $1 VmSize + line $1 VmData + } + + echo "### Before GC" >> ./output.md + table beforeGc + echo >> ./output.md + + echo "### After GC" >> ./output.md + table afterGc + echo >> ./output.md + + echo "### After Request" >> ./output.md + table afterRequest + echo >> ./output.md + + # Determine if this is a significant change (more than 5% increase) + if [ "$(echo "$RES" | jq -r '.afterGc.VmRSS.diff_percent | tonumber > 5')" = "true" ]; then + echo "⚠️ **Warning**: Memory usage has increased by more than 5%. Please verify this is not an unintended change." >> ./output.md echo >> ./output.md fi diff --git a/.github/workflows/storybook.yml b/.github/workflows/storybook.yml index c28b1f6e93..0bfb7f4c9c 100644 --- a/.github/workflows/storybook.yml +++ b/.github/workflows/storybook.yml @@ -22,12 +22,12 @@ jobs: NODE_OPTIONS: "--max_old_space_size=7168" steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 if: github.event_name != 'pull_request_target' with: fetch-depth: 0 submodules: true - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 if: github.event_name == 'pull_request_target' with: fetch-depth: 0 @@ -37,9 +37,9 @@ jobs: if: github.event_name == 'pull_request_target' run: git checkout "$(git rev-list --parents -n1 HEAD | cut -d" " -f3)" - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/test-backend.yml b/.github/workflows/test-backend.yml index 562ec76b85..29e634f84b 100644 --- a/.github/workflows/test-backend.yml +++ b/.github/workflows/test-backend.yml @@ -48,13 +48,20 @@ jobs: image: redis:7 ports: - 56312:6379 + meilisearch: + image: getmeili/meilisearch:v1.38.2 + ports: + - 57712:7700 + env: + MEILI_NO_ANALYTICS: true + MEILI_ENV: development steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Get current date id: current-date run: echo "today=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT @@ -86,7 +93,7 @@ jobs: fi done - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: ${{ matrix.node-version-file }} cache: 'pnpm' @@ -129,13 +136,13 @@ jobs: - 56312:6379 steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: ${{ matrix.node-version-file }} cache: 'pnpm' @@ -173,16 +180,16 @@ jobs: POSTGRES_HOST_AUTH_METHOD: trust steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Get current date id: current-date run: echo "today=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: ${{ matrix.node-version-file }} cache: 'pnpm' diff --git a/.github/workflows/test-federation.yml b/.github/workflows/test-federation.yml index 7f8fe547e1..27049ecd42 100644 --- a/.github/workflows/test-federation.yml +++ b/.github/workflows/test-federation.yml @@ -36,7 +36,7 @@ jobs: with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Get current date id: current-date run: echo "today=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT @@ -68,7 +68,7 @@ jobs: fi done - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: ${{ matrix.node-version-file }} cache: 'pnpm' diff --git a/.github/workflows/test-frontend.yml b/.github/workflows/test-frontend.yml index 52723e894c..1125565d8b 100644 --- a/.github/workflows/test-frontend.yml +++ b/.github/workflows/test-frontend.yml @@ -28,13 +28,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' @@ -76,7 +76,7 @@ jobs: - 56312:6379 steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true # https://github.com/cypress-io/cypress-docker-images/issues/150 @@ -86,9 +86,9 @@ jobs: #- uses: browser-actions/setup-firefox@latest # if: ${{ matrix.browser == 'firefox' }} - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/test-misskey-js.yml b/.github/workflows/test-misskey-js.yml index 428cbce3b8..54cf1c318a 100644 --- a/.github/workflows/test-misskey-js.yml +++ b/.github/workflows/test-misskey-js.yml @@ -22,13 +22,13 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@v6.0.2 - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/test-production.yml b/.github/workflows/test-production.yml index 9c0ea4d738..319ff6e5f8 100644 --- a/.github/workflows/test-production.yml +++ b/.github/workflows/test-production.yml @@ -16,13 +16,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.github/workflows/validate-api-json.yml b/.github/workflows/validate-api-json.yml index 8ffc60fc6e..f2e8381344 100644 --- a/.github/workflows/validate-api-json.yml +++ b/.github/workflows/validate-api-json.yml @@ -17,13 +17,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 with: submodules: true - name: Setup pnpm - uses: pnpm/action-setup@v4.2.0 + uses: pnpm/action-setup@v4.4.0 - name: Use Node.js - uses: actions/setup-node@v6.1.0 + uses: actions/setup-node@v6.3.0 with: node-version-file: '.node-version' cache: 'pnpm' diff --git a/.gitignore b/.gitignore index ac7502f384..7839e4de66 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ docker-compose.yml built built-test js-built +src-js /data /.cache-loader /db diff --git a/CHANGELOG.md b/CHANGELOG.md index aa87591710..b8e46890ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,18 +1,116 @@ -## 2025.12.2 +## Unreleased -### Note -v2025.12.0で行われた「configの`trustProxy`のデフォルト値を`false`に変更」について、正しく環境に応じた設定を行わないとサインインが困難になるといった状態を緩和するために、以前のデフォルト値に戻す暫定対応を行いました。 +### General +- Feat: ユーザーミュートの適用範囲から通知を除外できるように + - タイムラインや検索等でノートが見えないようにしつつ、通知は引き続き受け取れるように設定することができるようになりました -**セキュリティを向上させるためには適切な設定を行うことを推奨しますが、間違った設定値を入れると上述のような不具合の原因となりますので、慎重に行ってください。** +### Client +- Enhance: ミュートの付与期間を自由に設定できるように +- Enhance: ロールの付与期間を自由に設定できるように + +### Server +- Fix: `/api-doc` にアクセスできない問題を修正 + + +## 2026.3.2 ### General - 依存関係の更新 ### Client -- Enhance: ミュートの付与期間を自由に設定できるように -- Enhance: ロールの付与期間を自由に設定できるように -- Fix: バージョン表記のないPlayが正しく動作しない問題を修正 +- Enhance: アプリ内ウィンドウの初期サイズを画面サイズに応じて自動で調整するように +- Fix: 絵文字パレットが空の状態でMisskeyについてのページが閲覧できない問題を修正 +- Fix: ウィンドウのタイトルをクリックしても最前面に出ないことがある問題を修正 +### Server +- Fix: 自分の行ったフォロワー限定投稿または指名投稿に自分自身でリアクションなどを行った場合のイベントが流れない問題を修正 +- Fix: 署名付きGETリクエストにおいてAcceptヘッダを署名の対象から除外(Acceptヘッダを正規化するCDNやリバースプロキシを使用している際に挙動がおかしくなる問題を修正) +- Fix: WebSocket接続におけるノートの非表示ロジックを修正 +- Fix: チャンネルミュートを有効にしている際に、一部のタイムラインやノート一覧が空になる問題を修正 +- Fix: 初期読込時に必要なフロントエンドのアセットがすべて読み込まれていない問題を修正 + + +## 2026.3.1 + +### General +- 依存関係の更新 + +### Server +- Fix: セキュリティに関する修正 + + +## 2026.3.0 + +### Note +- `users/following` の `birthday` プロパティは非推奨になりました。代わりに `users/get-following-users-by-birthday` をご利用ください。 + +### General +- Enhance: 「もうすぐ誕生日のユーザー」ウィジェットで、誕生日が至近のユーザーも表示できるように + (Cherry-picked from https://github.com/MisskeyIO/misskey) + - 「今日誕生日のユーザー」は「もうすぐ誕生日のユーザー」に名称変更されました +- Fix: ユーザーハッシュタグページでユーザーの読み込みが重複する問題を修正 +- 依存関係の更新 + +### Client +- Enhance: ドライブのファイル一覧で自動でもっと見るを利用可能に +- Enhance: ウィジェットの表示設定をプレビューを見ながら行えるように +- Enhance: ウィジェットの設定項目のラベルの多言語対応 +- Enhance: 画面幅が広いときにメディアを横並びで表示できるようにするオプションを追加 +- Enhance: パフォーマンスの向上 +- Fix: ドライブクリーナーでファイルを削除しても画面に反映されない問題を修正 #16061 +- Fix: 非ログイン時にログインを求めるダイアログが表示された後にダイアログのぼかしが解除されず操作不能になることがある問題を修正 +- Fix: ドライブのソートが「登録日(昇順)」の場合に正しく動作しない問題を修正 +- Fix: 高度なMFMのピッカーを使用する際の挙動を改善 +- Fix: 管理画面でアーカイブ済のお知らせを表示した際にアクティブなお知らせが多い旨の警告が出る問題を修正 +- Fix: ファイルタブのセンシティブメディアを開く際に確認ダイアログを出す設定が適用されない問題を修正 +- Fix: 2月29日を誕生日に設定している場合、閏年以外は3月1日を誕生日として扱うように修正 +- Fix: `Mk:C:container` の `borderWidth` が正しく反映されない問題を修正 +- Fix: mCaptchaが正しく動作しない問題を修正 +- Fix: 非ログイン時にリバーシの対局が表示されない問題を修正 +- Fix: ノートの詳細表示でリアクションが全件表示されない問題を修正 +- Fix: 動画埋め込みプレイヤーなどの一部ウィンドウで、ウィンドウのサイズ変更や移動が正常に行えない問題を修正 +- Fix: 画像エフェクトの修正 + - 塗りつぶし・モザイク・ぼかしエフェクトを回転させると歪む問題を修正 + - モザイクの格子のサイズが画像の縦横比によって長方形となる問題を修正 + - モザイクの色味がより自然になるように修正 + - ぼかしに不自然な縦線が入る問題を修正 +- Fix: フォロー承認通知でフォローされた際のメッセージの絵文字が表示されない問題を修正 +- Fix: HTTP環境など(Secure Contextのない環境)で、設定画面が閲覧できない問題を修正 + +### Server +- Enhance: OAuthのクライアント情報取得(Client Information Discovery)において、IndieWeb Living Standard 11 July 2024で定義されているJSONドキュメント形式に対応しました + - JSONによるClient Information Discoveryを行うには、レスポンスの`Content-Type`ヘッダーが`application/json`である必要があります + - 従来の実装(12 February 2022版・HTML Microformat形式)も引き続きサポートされます +- Enhance: メモリ使用量を削減 +- Fix: `/admin/get-user-ips` エンドポイントのアクセス権限を管理者のみに修正 + +## 2025.12.2 + +### Note +v2025.12.0で行われた「configの`trustProxy`のデフォルト値を`false`に変更」について、正しく環境に応じた設定を行わないとサインインが困難になるといった状態を緩和するために、以下の対応を行いました。 + +**正しく設定しないと、上記のような不具合の原因となったり、セキュリティリスクが高まったりする可能性があります。必ず現在のconfigをご確認の上、必要に応じて値を変更してください。** + +- `trustProxy`について、デフォルト(configに値が設定されていない状態)ではループバックアドレスとローカルIPアドレス空間を信頼するようにしました。 +- `trustProxy`の設定方法について、より詳細に記述しました。 +- リバースプロキシやCDNなどのより上流のレイヤでレートリミットを設定したい場合や、緊急時の一時的な緩和策として、Misskey内部でのIPアドレスペースでのレートリミットを無効化できるようにしました。 + +### General +- 依存関係の更新 + +### Client +- Enhance: デッキのUI説明を追加 +- Enhance: 設定がブラウザによって消去されないようにするオプションを追加 +- Fix: バージョン表記のないPlayが正しく動作しない問題を修正 + バージョン表記のないものは v0.x 系として実行されます。v1.x 系で動作させたい場合は必ずバージョン表記を含めてください。 +- Fix: デッキUIでメニュー位置を下にしているとプロファイル削除ボタンが表示されないのを修正 +- Fix: 一部のUnicode絵文字のリアクションがボタンにならない問題を修正 + +### Server +- Enhance: Misskey内部でのIPアドレスペースでのレートリミットを無効化できるように + - リバースプロキシやCDNなど別のレイヤで別途レートリミットを設定する場合や、ローカルでのテスト用途等として利用することを想定しています。 + - デフォルトは `enableIpRateLimit: true`(Misskey内部でのIPアドレスペースでのレートリミットは有効)です。 +- Fix: コントロールパネルのジョブキューページで使用される一部APIの応答速度を改善 ## 2025.12.1 diff --git a/COPYING b/COPYING index 7635bfc913..a17c82c002 100644 --- a/COPYING +++ b/COPYING @@ -1,5 +1,5 @@ Unless otherwise stated this repository is -Copyright © 2014-2025 syuilo and contributors +Copyright © 2014-2026 syuilo and contributors And is distributed under The GNU Affero General Public License Version 3, you should have received a copy of the license file as LICENSE. diff --git a/Dockerfile b/Dockerfile index 02739d9ca2..19f9e8c9dc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ -# syntax = docker/dockerfile:1.4 +# syntax = docker/dockerfile:1.21 -ARG NODE_VERSION=22.15.0-bookworm +ARG NODE_VERSION=22.22.0-bookworm # build assets & compile TypeScript @@ -102,6 +102,7 @@ COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-js/ COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-reversi/built ./packages/misskey-reversi/built COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-bubble-game/built ./packages/misskey-bubble-game/built COPY --chown=misskey:misskey --from=native-builder /misskey/packages/backend/built ./packages/backend/built +COPY --chown=misskey:misskey --from=native-builder /misskey/packages/backend/src-js ./packages/backend/src-js COPY --chown=misskey:misskey --from=native-builder /misskey/packages/i18n/built ./packages/i18n/built COPY --chown=misskey:misskey --from=native-builder /misskey/fluent-emojis /misskey/fluent-emojis COPY --chown=misskey:misskey . ./ diff --git a/README.md b/README.md index a73102d713..e3261d13c2 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/misskey-dev/misskey) + + ## Thanks @@ -49,3 +51,13 @@ Thanks to [Crowdin](https://crowdin.com/) for providing the localization platfor Docker Thanks to [Docker](https://hub.docker.com/) for providing the container platform that helps us run Misskey in production. + +--- + +
+ +Support us with a ⭐ ! + +[![Star History Chart](https://api.star-history.com/svg?repos=misskey-dev/misskey&type=Date)](https://star-history.com/#misskey-dev/misskey&Date) + +
diff --git a/locales/ar-SA.yml b/locales/ar-SA.yml index d130d4b4b3..a72429e941 100644 --- a/locales/ar-SA.yml +++ b/locales/ar-SA.yml @@ -1365,6 +1365,14 @@ _widgets: userList: "قائمة المستخدمين" _userList: chooseList: "اختر قائمة" +_widgetOptions: + height: "الإرتفاع" + _button: + colored: "ملوّن" + _clock: + size: "الحجم" + _birthdayFollowings: + period: "المدة" _cw: hide: "إخفاء" show: "عرض المزيد" diff --git a/locales/bn-BD.yml b/locales/bn-BD.yml index e7d391cd70..9af4fc0ec4 100644 --- a/locales/bn-BD.yml +++ b/locales/bn-BD.yml @@ -1137,6 +1137,14 @@ _widgets: aichan: "আই চান" _userList: chooseList: "লিস্ট নির্বাচন করুন" +_widgetOptions: + height: "উচ্চতা" + _button: + colored: "রঙ্গিন" + _clock: + size: "আকার" + _birthdayFollowings: + period: "ব্যাপ্তিকাল" _cw: hide: "লুকান" show: "আরও দেখুন" diff --git a/locales/ca-ES.yml b/locales/ca-ES.yml index 59768668ef..f2867585c2 100644 --- a/locales/ca-ES.yml +++ b/locales/ca-ES.yml @@ -264,7 +264,7 @@ noJobs: "No hi ha feines" federating: "Federant" blocked: "Bloquejat" suspended: "Anul·lar subscripció " -all: "tot" +all: "Tot" subscribing: "Subscrit a" publishing: "S'està publicant" notResponding: "Sense resposta" @@ -543,6 +543,7 @@ regenerate: "Regenera" fontSize: "Mida del text" mediaListWithOneImageAppearance: "Altura de la llista de fitxers amb una única imatge" limitTo: "Limita a {x}" +showMediaListByGridInWideArea: "Mostra la llista de medis en vista quadrícula quan l'amplada de la pantalla ho permeti" noFollowRequests: "No tens sol·licituds de seguiment" openImageInNewTab: "Obre imatges a una nova pestanya" dashboard: "Tauler de control" @@ -1389,7 +1390,7 @@ defaultCompressionLevel_description: "Si el redueixes augmentaràs la qualitat d inMinutes: "Minut(s)" inDays: "Di(a)(es)" safeModeEnabled: "Mode segur activat" -pluginsAreDisabledBecauseSafeMode: "Els afegits no estan activats perquè el mode segur està activat." +pluginsAreDisabledBecauseSafeMode: "Les extensions no estan activades perquè el mode segur està activat." customCssIsDisabledBecauseSafeMode: "El CSS personalitzat no s'aplica perquè el mode segur es troba activat." themeIsDefaultBecauseSafeMode: "El tema predeterminat es farà servir mentre el mode segur estigui activat. Una vegada es desactivi el mode segur es restablirà el tema escollit." thankYouForTestingBeta: "Gràcies per ajudar-nos a provar la versió beta!" @@ -1406,6 +1407,7 @@ youAreAdmin: "Ets l'administrador " frame: "Marc" presets: "Predefinit" zeroPadding: "Sense omplir" +nothingToConfigure: "No hi ha res a configurar" _imageEditing: _vars: caption: "Títol de l'arxiu" @@ -1550,6 +1552,9 @@ _settings: showPageTabBarBottom: "Mostrar les pestanyes de les línies de temps a la part inferior" emojiPaletteBanner: "Pots registrar ajustos preestablerts com paletes perquè es mostrin permanentment al selector d'emojis, o personalitzar la configuració de visió del selector." enableAnimatedImages: "Activar imatges animades" + settingsPersistence_title: "Persistència de la configuració " + settingsPersistence_description1: "Habilitar la persistència de la configuració permet que no es perdi la informació de la configuració " + settingsPersistence_description2: "Depenent de l'entorn pot ser que no puguis habilitar aquesta opció." _chat: showSenderName: "Mostrar el nom del remitent" sendOnEnter: "Introdueix per enviar" @@ -1609,8 +1614,8 @@ _bubbleGame: highScore: "Millor puntuació " maxChain: "Nombre màxim de combos" yen: "{yen}Ien" - estimatedQty: "{qty}peces" - scoreSweets: "{onigiriQtyWithUnit}ongiris" + estimatedQty: "{qty} Peces" + scoreSweets: "{onigiriQtyWithUnit} Boles d'arròs " _howToPlay: section1: "Ajusta la posició i deixa caure l'objecte dintre la caixa." section2: "Quan dos objectes del mateix tipus es toquen, canviaran en un objecte diferent i guanyares punts." @@ -2180,8 +2185,8 @@ _email: title: "Has rebut una sol·licitud de seguiment" _plugin: install: "Instal·lar un afegit " - installWarn: "Si us plau, no instal·lis afegits que no siguin de confiança." - manage: "Gestionar els afegits" + installWarn: "Si us plau, no instal·lis extensions que no siguin de confiança." + manage: "Gestiona les extensions" viewSource: "Veure l'origen " viewLog: "Mostra el registre" _preferencesBackups: @@ -2541,6 +2546,44 @@ _widgets: clicker: "Clicker" birthdayFollowings: "Usuaris que fan l'aniversari avui" chat: "Xateja amb aquest usuari" +_widgetOptions: + showHeader: "Mostrar la capçalera" + transparent: "Fons transparent" + height: "Alçada " + _button: + colored: "Colorit" + _clock: + size: "Mida" + thickness: "Amplada de l'agulla " + thicknessThin: "Esvelt " + thicknessMedium: "Normal" + thicknessThick: "Gruixut " + graduations: "Marques de l'esfera " + graduationDots: "Punt" + graduationArabic: "Nombres àrabs " + fadeGraduations: "Efecte gradient " + sAnimation: "Animació de la maneta dels segons" + sAnimationElastic: "Real" + sAnimationEaseOut: "Suau" + twentyFour: "Format 24 hores" + labelTime: "Temps" + labelTz: "Fus horari" + labelTimeAndTz: "Hora i fus horari" + timezone: "Fus horari" + showMs: "Mostrar mil·lisegons" + showLabel: "Mostrar etiqueta" + _jobQueue: + sound: "Reprodueix so" + _rss: + url: "URL del canal RSS" + refreshIntervalSec: "Interval d'actualitzacions (segons)" + maxEntries: "Nombre màxim d'entrades a mostrar" + _rssTicker: + shuffle: "Visualització aleatòria " + duration: "Velocitat desplaçament bàner informatiu " + reverse: "Desplaçament contrari" + _birthdayFollowings: + period: "Període" _cw: hide: "Amagar" show: "Carregar més" @@ -2816,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "L'amplada mínima es farà servir quan \"Ajust automàtic de l'amplada\" estigui activat" flexible: "Ajust automàtic de l'amplada" enableSyncBetweenDevicesForProfiles: "Activar la sincronització de la informació de perfils de dispositiu a dispositiu" + showHowToUse: "Veure la descripció de la interfície d'usuari " + _howToUse: + addColumn_title: "Afegir columna" + addColumn_description: "Pots seleccionar i afegir tipus de columnes." + settings_title: "Configuració de la interfície d'usuari " + settings_description: "Pots configurar la interfície d'usuari amb detall." + switchProfile_title: "Canviar perfil" + switchProfile_description: "Pots desar el disseny de la interfície d'usuari com un perfil i anar canviant entre ells quan vulguis." _columns: main: "Principal" widgets: "Ginys" @@ -3299,7 +3350,6 @@ _imageEffector: title: "Efecte" addEffect: "Afegeix un efecte" discardChangesConfirm: "Vols descartar els canvis i sortir?" - nothingToConfigure: "No hi ha opcions de configuració disponibles" failedToLoadImage: "Error en carregar la imatge" _fxs: chromaticAberration: "Aberració cromàtica" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "Llindar" centerX: "Centre de X" centerY: "Centre de Y" - zoomLinesSmoothing: "Suavitzat" - zoomLinesSmoothingDescription: "Els paràmetres de suavitzat i amplada de línia en augmentar no es poden fer servir junts." - zoomLinesThreshold: "Amplada de línia a l'augmentar " + density: "Densitat" + zoomLinesOutlineThickness: "Amplada de les vores exteriors" zoomLinesMaskSize: "Diàmetre del centre" - zoomLinesBlack: "Obscurir" circle: "Cercle" drafts: "Esborrany " _drafts: diff --git a/locales/cs-CZ.yml b/locales/cs-CZ.yml index 4738b1de13..c8d2ff6565 100644 --- a/locales/cs-CZ.yml +++ b/locales/cs-CZ.yml @@ -130,6 +130,7 @@ reactions: "Reakce" reactionSettingDescription2: "Přetažením změníte pořadí, kliknutím smažete, zmáčkněte \"+\" k přidání" rememberNoteVisibility: "Zapamatovat nastavení zobrazení poznámky" attachCancel: "Odstranit přílohu" +deleteFile: "Smazat soubor" markAsSensitive: "Označit jako NSFW" unmarkAsSensitive: "Odznačit jako NSFW" enterFileName: "Zadejte název souboru" @@ -205,6 +206,7 @@ blockThisInstance: "Blokovat tuto instanci" silenceThisInstance: "Utišit tuto instanci" operations: "Operace" software: "Software" +softwareName: "Software" version: "Verze" metadata: "Metadata" withNFiles: "{n} soubor(ů)" @@ -231,6 +233,7 @@ noteDeleteConfirm: "Jste si jistí že chcete smazat tuhle poznámku?" pinLimitExceeded: "Nemůžete připnout další poznámky." done: "Hotovo" processing: "Zpracovávám" +preprocessing: "Připravuji..." preview: "Náhled" default: "Výchozí" defaultValueIs: "Základní hodnota: {value}" @@ -265,6 +268,7 @@ removed: "Smazáno" removeAreYouSure: "Jste si jistí že chcete smazat \"{x}\"?" deleteAreYouSure: "Jste si jistí že chcete smazat \"{x}\"?" resetAreYouSure: "Opravdu resetovat?" +areYouSure: "Jste si jistí?" saved: "Uloženo" upload: "Nahrát soubory" keepOriginalUploading: "Ponechat originální obrázek" @@ -275,9 +279,12 @@ uploadFromUrl: "Nahrát z URL adresy" uploadFromUrlDescription: "URL adresa souboru, který chcete nahrát" uploadFromUrlRequested: "Upload zažádán" uploadFromUrlMayTakeTime: "Může trvat nějakou dobu, dokud nebude dokončeno nahrávání." +uploadNFiles: "Uploadovat {n} souborů" explore: "Objevovat" messageRead: "Přečtené" +readAllChatMessages: "Označit všechny zprávy za přečtené" noMoreHistory: "To je vše" +startChat: "Začít chat" nUsersRead: "přečteno {n} uživateli" agreeTo: "Souhlasím s {0}" agree: "Souhlasím" @@ -308,12 +315,15 @@ selectFile: "Vybrat soubor" selectFiles: "Vybrat soubory" selectFolder: "Vyberte složku" selectFolders: "Vyberte složky" +fileNotSelected: "Nebyl vybrán žádný soubor" renameFile: "Přejmenovat soubor" folderName: "Název složky" createFolder: "Vytvořit složku" renameFolder: "Přejmenovat složku" deleteFolder: "Odstranit složku" +folder: "Složka " addFile: "Přidat soubor" +showFile: "Procházet soubory" emptyDrive: "Váš disk je prázdný" emptyFolder: "Tato složka je prázdná" unableToDelete: "Nelze smazat" @@ -424,6 +434,7 @@ totp: "Ověřovací aplikace" totpDescription: "Použít ověřovací aplikaci pro použití jednorázových hesel" moderator: "Moderátor" moderation: "Moderování" +moderationNote: "Poznámka moderátora" nUsersMentioned: "{n} uživatelů zmínilo" securityKeyAndPasskey: "Bezpečnostní klíče a tokeny" securityKey: "Bezpečnostní klíč" @@ -479,7 +490,9 @@ uiLanguage: "Jazyk uživatelského rozhraní" aboutX: "O {x}" emojiStyle: "Styl emoji" native: "Výchozí" +menuStyle: "Styl nabídky" style: "Vzhled" +drawer: "Boční menu" popup: "Vyskakovací okno" showNoteActionsOnlyHover: "Zobrazit akce poznámky jenom při naběhnutí myši" noHistory: "Žádná historie" @@ -535,6 +548,7 @@ deleteAll: "Smazat vše" showFixedPostForm: "Zobrazit formulář pro nové příspěvky nad časovou osou" showFixedPostFormInChannel: "Zobrazit vkládací formulář na vrcholu časové osy (Kanály)" newNoteRecived: "Jsou k dispozici nové poznámky" +newNote: "Nová poznámka" sounds: "Zvuky" sound: "Zvuky" listen: "Poslouchat" @@ -614,6 +628,7 @@ medium: "Střední" small: "Malé" generateAccessToken: "Vygenerovat přístupový token" permission: "Oprávnění" +adminPermission: "Administrátorská práva" enableAll: "Povolit vše" disableAll: "Vypnout vše" tokenRequested: "Povolit přístup k účtu" @@ -889,6 +904,9 @@ oneHour: "1 hodina" oneDay: "1 den" oneWeek: "1 týden" oneMonth: "1 měsíc" +threeMonths: "3 měsíce" +oneYear: "1 rok" +threeDays: "3 dny" reflectMayTakeTime: "Může trvat nějakou dobu, než se projeví změny." failedToFetchAccountInformation: "Nepodařily se načíst informace o účtě" rateLimitExceeded: "Překročení rychlostního limitu" @@ -1026,6 +1044,8 @@ showClipButtonInNoteFooter: "Přidat \"Připnout\" do akčního menu poznámky" noteIdOrUrl: "ID nebo URL poznámky" video: "Video" videos: "Videa" +audio: "Zvuk" +audioFiles: "Zvuk" dataSaver: "Spořič dat" accountMigration: "Migrace účtu" accountMoved: "Tenhle uživatel se přesunul na nový účet:" @@ -1053,6 +1073,8 @@ preservedUsernames: "Rezervované uživatelské jména" preservedUsernamesDescription: "Seznam uživatelských jmén na rezervaci oddělené mezerama. Tyhle jména se potom nebudou moc použít při normálním procesu vytvoření účtu ale můžou být použiti manuálně administratorém. Existujících účtů se to nedotkne." createNoteFromTheFile: "Vytvořit poznámku z tohodle souboru" archive: "Archiv" +archived: "Archivované" +unarchive: "Obnovit" channelArchiveConfirmTitle: "Opravdu chcete archivovat {name}?" channelArchiveConfirmDescription: "Archivovaný kanál se objeví v seznamu kanálů nebo ve výsledcích hledání. Nové poznámky se nedají vložit do seznamu." thisChannelArchived: "Tenhle kanál je archivovaný" @@ -1099,6 +1121,7 @@ doYouAgree: "Souhlasíte?" beSureToReadThisAsItIsImportant: "Přečtěte si prosím tyto důležité informace." iHaveReadXCarefullyAndAgree: "Přečetl jsem si text \"{x}\" a souhlasím s ním." icon: "Avatar" +forYou: "Pro vás" replies: "Odpovědět" renotes: "Přeposlat" sourceCode: "Zdrojový kód" @@ -1789,6 +1812,14 @@ _widgets: _userList: chooseList: "Vybrat seznam" clicker: "Clicker" +_widgetOptions: + height: "Výška" + _button: + colored: "Barevné" + _clock: + size: "Velikost" + _birthdayFollowings: + period: "Trvání" _cw: hide: "Skrýt" show: "Zobrazit více" diff --git a/locales/de-DE.yml b/locales/de-DE.yml index 33e19f1cc1..cc645d83cf 100644 --- a/locales/de-DE.yml +++ b/locales/de-DE.yml @@ -83,6 +83,7 @@ files: "Dateien" download: "Herunterladen" driveFileDeleteConfirm: "Möchtest du die Datei „{name}“ wirklich löschen? Einige Inhalte, die diese Datei verwenden, werden auch verschwinden." unfollowConfirm: "Möchtest du {name} wirklich nicht mehr folgen?" +cancelFollowRequestConfirm: "Möchten Sie die Voll-Anfrage an {name} zurückziehen?" rejectFollowRequestConfirm: "Möchtest du die Follow-Anfrage von {name} ablehnen?" exportRequested: "Du hast einen Export angefragt. Dies kann etwas Zeit in Anspruch nehmen. Sobald der Export abgeschlossen ist, wird er deiner Drive hinzugefügt." importRequested: "Du hast einen Import angefragt. Dies kann etwas Zeit in Anspruch nehmen." @@ -254,6 +255,7 @@ noteDeleteConfirm: "Möchtest du diese Notiz wirklich löschen?" pinLimitExceeded: "Du kannst nicht noch mehr Notizen anheften." done: "Fertig" processing: "In Bearbeitung …" +preprocessing: "In Vorbereitung" preview: "Vorschau" default: "Standard" defaultValueIs: "Standardwert: {value}" @@ -302,6 +304,7 @@ uploadFromUrlMayTakeTime: "Es kann eine Weile dauern, bis das Hochladen abgeschl uploadNFiles: "Lade {n} Dateien hoch" explore: "Erkunden" messageRead: "Gelesen" +readAllChatMessages: "Alle Nachrichten als gelesen markieren" noMoreHistory: "Kein weiterer Verlauf vorhanden" startChat: "Chat starten" nUsersRead: "Von {n} Benutzern gelesen" @@ -334,6 +337,7 @@ fileName: "Dateiname" selectFile: "Datei auswählen" selectFiles: "Dateien auswählen" selectFolder: "Ordner auswählen" +unselectFolder: "Ordnerauswahl aufheben" selectFolders: "Ordner auswählen" fileNotSelected: "Keine Datei ausgewählt" renameFile: "Datei umbenennen" @@ -346,6 +350,7 @@ addFile: "Datei hinzufügen" showFile: "Datei anzeigen" emptyDrive: "Deine Drive ist leer" emptyFolder: "Dieser Ordner ist leer" +dropHereToUpload: "Dateien hier ablegen, um sie hochzuladen." unableToDelete: "Nicht löschbar" inputNewFileName: "Gib einen neuen Dateinamen ein" inputNewDescription: "Gib eine neue Beschreibung ein" @@ -538,6 +543,7 @@ regenerate: "Regenerieren" fontSize: "Schriftgröße" mediaListWithOneImageAppearance: "Höhe von Medienlisten mit nur einem Bild" limitTo: "Auf {x} begrenzen" +showMediaListByGridInWideArea: "Medienlisten auf breiteren Bildschirmen nebeneinander anzeigen" noFollowRequests: "Keine ausstehenden Follow-Anfragen vorhanden" openImageInNewTab: "Bilder in neuem Tab öffnen" dashboard: "Dashboard" @@ -773,6 +779,7 @@ lockedAccountInfo: "Auch wenn du Follow-Anfragen auf manuelle Bestätigung setzt alwaysMarkSensitive: "Medien standardmäßig als sensibel markieren" loadRawImages: "Anstatt Vorschaubilder immer Originalbilder anzeigen" disableShowingAnimatedImages: "Animierte Bilder nicht abspielen" +disableShowingAnimatedImages_caption: "Unabhängig von dieser Einstellung kann es vorkommen, dass animierte Bilder nicht abgespielt werden, wenn z. B. die Barrierefreiheits- oder Energiespareinstellungen des Browsers oder des Betriebssystems eingreifen." highlightSensitiveMedia: "Sensitive Medien markieren" verificationEmailSent: "Eine Bestätigungsmail wurde an deine Email-Adresse versendet. Besuche den dort enthaltenen Link, um die Verifizierung abzuschließen." notSet: "Nicht konfiguriert" @@ -1020,6 +1027,8 @@ pushNotificationNotSupported: "Entweder dein Browser oder deine Instanz unterst sendPushNotificationReadMessage: "Push-Benachrichtigungen löschen, sobald sie gelesen wurden" sendPushNotificationReadMessageCaption: "Dies kann gegebenenfalls den Batterieverbrauch deines Gerätes erhöhen." pleaseAllowPushNotification: "Bitte erlauben Sie Benachrichtigungen in Ihrem Browser." +browserPushNotificationDisabled: "Das Abrufen der Berechtigung zum Senden von Benachrichtigungen ist fehlgeschlagen." +browserPushNotificationDisabledDescription: "Sie haben keine Berechtigung, Benachrichtigungen von {serverName} zu senden. Bitte erlauben Sie Benachrichtigungen in den Browser-Einstellungen und versuchen Sie es erneut." windowMaximize: "Maximieren" windowMinimize: "Minimieren" windowRestore: "Wiederherstellen" @@ -1095,6 +1104,7 @@ prohibitedWordsDescription2: "Durch die Verwendung von Leerzeichen können AND-V hiddenTags: "Ausgeblendete Hashtags" hiddenTagsDescription: "Die hier eingestellten Tags werden nicht mehr in den Trends angezeigt. Mit der Umschalttaste können mehrere ausgewählt werden." notesSearchNotAvailable: "Die Notizsuche ist nicht verfügbar." +usersSearchNotAvailable: "Die Benutzersuche ist nicht verfügbar." license: "Lizenz" unfavoriteConfirm: "Wirklich aus Favoriten entfernen?" myClips: "Meine Clips" @@ -1169,6 +1179,7 @@ installed: "Installiert" branding: "Branding" enableServerMachineStats: "Hardwareinformationen des Servers veröffentlichen" enableIdenticonGeneration: "Generierung von Benutzer-Identicons aktivieren" +showRoleBadgesOfRemoteUsers: "Rollensymbole anzeigen, die Remote-Benutzern zugewiesen wurden." turnOffToImprovePerformance: "Deaktivierung kann zu höherer Leistung führen." createInviteCode: "Einladung erstellen" createWithOptions: "Einladung mit Optionen erstellen" @@ -1317,6 +1328,7 @@ acknowledgeNotesAndEnable: "Schalten Sie dies erst ein, wenn Sie die Vorsichtsma federationSpecified: "Dieser Server arbeitet mit Whitelist-Föderation. Er kann nicht mit anderen als den vom Administrator angegebenen Servern interagieren." federationDisabled: "Föderation ist auf diesem Server deaktiviert. Es ist nicht möglich, mit Benutzern auf anderen Servern zu interagieren." draft: "Entwurf" +draftsAndScheduledNotes: "Entwürfe und geplante Beiträge" confirmOnReact: "Reagieren bestätigen" reactAreYouSure: "Willst du eine \"{emoji}\"-Reaktion hinzufügen?" markAsSensitiveConfirm: "Möchtest du dieses Medium als sensibel kennzeichnen?" @@ -1345,6 +1357,7 @@ textCount: "Zeichenanzahl" information: "Über" chat: "Chat" directMessage: "Mit dem Benutzer chatten" +directMessage_short: "Nachrichten" migrateOldSettings: "Alte Client-Einstellungen migrieren" migrateOldSettings_description: "Dies sollte normalerweise automatisch geschehen, aber wenn die Migration aus irgendeinem Grund nicht erfolgreich war, kannst du den Migrationsprozess selbst manuell auslösen. Die aktuellen Konfigurationsinformationen werden dabei überschrieben." compress: "Komprimieren" @@ -1372,28 +1385,83 @@ redisplayAllTips: "Alle „Tipps und Tricks“ wieder anzeigen" hideAllTips: "Alle „Tipps und Tricks“ ausblenden" defaultImageCompressionLevel: "Standard-Bildkomprimierungsstufe" defaultImageCompressionLevel_description: "Ein niedrigerer Wert erhält die Bildqualität, erhöht aber die Dateigröße.
Höhere Werte reduzieren die Dateigröße, verringern aber die Bildqualität." +defaultCompressionLevel: "Standard-Kompressionsgrad" +defaultCompressionLevel_description: "Bei einem niedrigeren Wert bleibt die Qualität erhalten, aber die Dateigröße nimmt zu.
Bei einem höheren Wert lässt sich die Dateigröße verringern, aber die Qualität nimmt ab." inMinutes: "Minute(n)" inDays: "Tag(en)" safeModeEnabled: "Der abgesicherte Modus ist aktiviert." +pluginsAreDisabledBecauseSafeMode: "Da der abgesicherte Modus aktiviert ist, sind alle Plugins deaktiviert." +customCssIsDisabledBecauseSafeMode: "Da der abgesicherte Modus aktiviert ist, wird benutzerdefiniertes CSS nicht angewendet." +themeIsDefaultBecauseSafeMode: "Solange der abgesicherte Modus aktiviert ist, wird das Standard-Theme verwendet. Wenn Sie den abgesicherten Modus deaktivieren, wird es wieder zurückgesetzt." +thankYouForTestingBeta: "Vielen Dank für Ihre Unterstützung beim Testen der Beta-Version!" +createUserSpecifiedNote: "Benutzerdefinierte Notiz erstellen" +schedulePost: "Beitrag planen" +scheduleToPostOnX: "Der Beitrag wird für {x} geplant.x" +scheduledToPostOnX: "Der Beitrag ist für {x} geplant." schedule: "Planen" scheduled: "Geplant" widgets: "Widgets" deviceInfo: "Geräteinformation" +deviceInfoDescription: "Bei technischen Anfragen kann es hilfreich sein, die folgenden Informationen anzugeben, da dies zur Lösung des Problems beitragen kann." youAreAdmin: "Sie sind ein Administrator" +frame: "Rahmen" presets: "Vorlage" +zeroPadding: "Nullauffüllung" +nothingToConfigure: "Es sind keine Einstellungen verfügbar" _imageEditing: _vars: + caption: "Dateibeschriftung" filename: "Dateiname" + filename_without_ext: "Dateiname ohne Erweiterung" + year: "Jahr der Aufnahme" + month: "Monat der Aufnahme" + day: "Tag der Aufnahme" + hour: "Stunde der Aufnahmezeit" + minute: "Minute der Aufnahmezeit" + second: "Sekunde der Aufnahmezeit" + camera_model: "Kameraname" + camera_lens_model: "Objektivname" + camera_mm: "Brennweite" + camera_mm_35: "Brennweite (35-mm-Äquivalent)" + camera_f: "Blende" + camera_s: "Verschlusszeit" + camera_iso: "ISO-Empfindlichkeit" + gps_lat: "Breitengrad" + gps_long: "Längengrad" _imageFrameEditor: + title: "Rahmenbearbeitung" + tip: "Sie können das Bild dekorieren, indem Sie einen Rahmen sowie ein Etikett mit Metadaten hinzufügen." header: "Kopfzeile" + footer: "Fußzeile" + borderThickness: "Randbreite" + labelThickness: "Beschriftungsbreite" + labelScale: "Etikettenskala" + centered: "Zentriert" + captionMain: "Überschrift (groß)" + captionSub: "Beschriftung (klein)" + availableVariables: "Verfügbare Variablen" + withQrCode: "QR-Code" + backgroundColor: "Hintergrundfarbe" + textColor: "Textfarbe" font: "Schriftart" fontSerif: "Serif" fontSansSerif: "Sans Serif" quitWithoutSaveConfirm: "Nicht gespeicherte Änderungen verwerfen?" + failedToLoadImage: "Das Laden des Bildes ist fehlgeschlagen." +_compression: + _quality: + high: "Hohe Qualität" + medium: "Mittlere Qualität" + low: "Niedrige Qualität" + _size: + large: "Groß" + medium: "Medium" + small: "Klein" _order: newest: "Neueste zuerst" oldest: "Älteste zuerst" _chat: + messages: "Nachrichten" noMessagesYet: "Noch keine Nachrichten" newMessage: "Neue Nachricht" individualChat: "Privater Chat" @@ -1481,6 +1549,12 @@ _settings: contentsUpdateFrequency_description2: "Wenn der Echtzeitmodus aktiviert ist, werden die Inhalte unabhängig von dieser Einstellung in Echtzeit aktualisiert." showUrlPreview: "URL-Vorschau anzeigen" showAvailableReactionsFirstInNote: "Zeige die verfügbaren Reaktionen im oberen Bereich an." + showPageTabBarBottom: "Tab-Leiste der Seite unten anzeigen" + emojiPaletteBanner: "Sie können Voreinstellungen, die im Emoji-Picker dauerhaft angezeigt werden sollen, als Palette registrieren oder die Anzeigeart des Pickers anpassen." + enableAnimatedImages: "Animierte Bilder aktivieren" + settingsPersistence_title: "Persistenz der Einstellungen" + settingsPersistence_description1: "Durch das Aktivieren der persistenten Speicherung der Einstellungen kann verhindert werden, dass Einstellungsinformationen verloren gehen." + settingsPersistence_description2: "Je nach Umgebung ist eine Aktivierung möglicherweise nicht möglich." _chat: showSenderName: "Name des Absenders anzeigen" sendOnEnter: "Eingabetaste sendet Nachricht" @@ -1489,6 +1563,8 @@ _preferencesProfile: profileNameDescription: "Lege einen Namen fest, der dieses Gerät identifiziert." profileNameDescription2: "Beispiel: \"Haupt-PC\", \"Smartphone\"" manageProfiles: "Profile verwalten" + shareSameProfileBetweenDevicesIsNotRecommended: "Es wird nicht empfohlen, dasselbe Profil auf mehreren Geräten zu teilen." + useSyncBetweenDevicesOptionIfYouWantToSyncSetting: "Wenn es Einstellungselemente gibt, die Sie über mehrere Geräte synchronisieren möchten, aktivieren Sie bitte die Option „Über mehrere Geräte synchronisieren“ jeweils einzeln." _preferencesBackup: autoBackup: "Automatische Sicherung" restoreFromBackup: "Wiederherstellen aus der Sicherung" @@ -1498,6 +1574,7 @@ _preferencesBackup: youNeedToNameYourProfileToEnableAutoBackup: "Um die automatische Sicherung zu aktivieren, müssen Profilnamen festgelegt werden." autoPreferencesBackupIsNotEnabledForThisDevice: "Die automatische Sicherung der Einstellungen ist auf diesem Gerät nicht aktiviert." backupFound: "Konfigurationssicherung gefunden." + forceBackup: "Erzwungenes Backup der Einstellungen" _accountSettings: requireSigninToViewContents: "Anmeldung erfordern, um Inhalte anzuzeigen" requireSigninToViewContentsDescription1: "Erfordere eine Anmeldung, um alle Notizen und andere Inhalte anzuzeigen, die du erstellt hast. Dadurch wird verhindert, dass Crawler deine Informationen sammeln." @@ -1654,6 +1731,10 @@ _serverSettings: fanoutTimelineDbFallback: "Auf die Datenbank zurückfallen" fanoutTimelineDbFallbackDescription: "Ist diese Option aktiviert, wird die Chronik auf zusätzliche Abfragen in der Datenbank zurückgreifen, wenn sich die Chronik nicht im Cache befindet. Eine Deaktivierung führt zu geringerer Serverlast, aber schränkt den Zeitraum der abrufbaren Chronik ein. " reactionsBufferingDescription: "Wenn diese Option aktiviert ist, kann sie die Leistung beim Erstellen von Reaktionen erheblich verbessern und die Belastung der Datenbank verringern. Allerdings steigt die Speichernutzung von Redis." + remoteNotesCleaning: "Automatische Bereinigung von Remote-Beiträgen" + remoteNotesCleaning_description: "Wenn diese Option aktiviert ist, werden Remote-Beiträge, die eine bestimmte Zeit überschritten haben, regelmäßig bereinigt, um ein Aufblähen der Datenbank zu verhindern." + remoteNotesCleaningMaxProcessingDuration: "Maximale fortlaufende Dauer des Reinigungsverarbeitungsprozesses" + remoteNotesCleaningExpiryDaysForEachNotes: "Mindestaufbewahrungsdauer für Notizen" inquiryUrl: "Kontakt-URL" inquiryUrlDescription: "Gib eine URL für das Kontaktformular der Serverbetreiber oder eine Webseite an, die Kontaktinformationen enthält." openRegistration: "Registrierung von Konten aktivieren" @@ -1672,6 +1753,11 @@ _serverSettings: userGeneratedContentsVisibilityForVisitor: "Sichtbarkeit von nutzergenerierten Inhalten für Gäste" userGeneratedContentsVisibilityForVisitor_description: "Dies ist nützlich, um zu verhindern, dass unangemessene Inhalte, die nicht gut moderiert sind, ungewollt über deinen eigenen Server im Internet veröffentlicht werden." userGeneratedContentsVisibilityForVisitor_description2: "Die uneingeschränkte Veröffentlichung aller Inhalte des Servers im Internet, einschließlich der vom Server empfangenen Fremdinhalte, birgt Risiken. Dies ist besonders wichtig für Betrachter, die sich des dezentralen Charakters der Inhalte nicht bewusst sind, da sie selbst fremde Inhalte fälschlicherweise als auf dem Server erstellte Inhalte wahrnehmen könnten." + restartServerSetupWizardConfirm_title: "Möchten Sie den Assistenten für die Ersteinrichtung des Servers erneut ausführen?" + restartServerSetupWizardConfirm_text: "Einige aktuelle Einstellungen werden zurückgesetzt." + entrancePageStyle: "Stil der Einstiegsseite" + showTimelineForVisitor: "Zeitleiste anzeigen" + showActivitiesForVisitor: "Aktivitäten anzeigen" _userGeneratedContentsVisibilityForVisitor: all: "Alles ist öffentlich" localOnly: "Nur lokale Inhalte werden veröffentlicht, fremde Inhalte bleiben privat" @@ -1994,6 +2080,7 @@ _role: canManageAvatarDecorations: "Profilbilddekorationen verwalten" driveCapacity: "Drive-Kapazität" maxFileSize: "Maximale Dateigröße, die hochgeladen werden kann" + maxFileSize_caption: "Bei einem Reverse Proxy oder einem CDN können andere vorgelagerte Konfigurationswerte vorhanden sein." alwaysMarkNsfw: "Dateien immer als NSFW markieren" canUpdateBioMedia: "Kann ein Profil- oder ein Bannerbild bearbeiten" pinMax: "Maximale Anzahl an angehefteten Notizen" @@ -2008,6 +2095,7 @@ _role: descriptionOfRateLimitFactor: "Je niedriger desto weniger restriktiv, je höher destro restriktiver." canHideAds: "Kann Werbung ausblenden" canSearchNotes: "Nutzung der Notizsuchfunktion" + canSearchUsers: "Nutzung der Benutzersuche" canUseTranslator: "Verwendung des Übersetzers" avatarDecorationLimit: "Maximale Anzahl an Profilbilddekorationen, die angebracht werden können" canImportAntennas: "Importieren von Antennen erlauben" @@ -2020,6 +2108,7 @@ _role: uploadableFileTypes_caption: "Gibt die zulässigen MIME-/Dateitypen an. Mehrere MIME-Typen können durch einen Zeilenumbruch getrennt angegeben werden, und Platzhalter können mit einem Sternchen (*) angegeben werden. (z. B. image/*)" uploadableFileTypes_caption2: "Bei manchen Dateien ist es nicht möglich, den Typ zu bestimmen. Um solche Dateien zuzulassen, füge {x} der Spezifikation hinzu." noteDraftLimit: "Anzahl der möglichen Entwürfe für serverseitige Notizen" + scheduledNoteLimit: "Maximale Anzahl gleichzeitig erstellbarer geplanter Beiträge" watermarkAvailable: "Kann die Wasserzeichenfunktion verwenden" _condition: roleAssignedTo: "Manuellen Rollen zugewiesen" @@ -2280,6 +2369,7 @@ _time: minute: "Minute(n)" hour: "Stunde(n)" day: "Tag(en)" + month: "Monat(e)" _2fa: alreadyRegistered: "Du hast bereits ein Gerät für Zwei-Faktor-Authentifizierung registriert." registerTOTP: "Authentifizierungs-App registrieren" @@ -2409,6 +2499,7 @@ _auth: scopeUser: "Als folgender Benutzer agieren" pleaseLogin: "Bitte logge dich ein, um Apps zu authorisieren." byClickingYouWillBeRedirectedToThisUrl: "Wenn der Zugang gewährt wird, wirst du automatisch zu folgender URL weitergeleitet" + alreadyAuthorized: "Dieser Anwendung wurde bereits Zugriff gewährt." _antennaSources: all: "Alle Notizen" homeTimeline: "Notizen von Benutzern, denen gefolgt wird" @@ -2455,6 +2546,44 @@ _widgets: clicker: "Klickzähler" birthdayFollowings: "Nutzer, die heute Geburtstag haben" chat: "Mit dem Benutzer chatten" +_widgetOptions: + showHeader: "Kopfzeile anzeigen" + transparent: "Hintergrund transparent machen" + height: "Höhe" + _button: + colored: "Farbig" + _clock: + size: "Größe" + thickness: "Dicke" + thicknessThin: "Dünn" + thicknessMedium: "Normal" + thicknessThick: "Dick" + graduations: "Zifferblattskala" + graduationDots: "Punkt" + graduationArabic: "Zahlen" + fadeGraduations: "Skala ausblenden" + sAnimation: "Zweite Animation" + sAnimationElastic: "Elastisch" + sAnimationEaseOut: "Weich" + twentyFour: "24-Stunden-Format" + labelTime: "Uhrzeit" + labelTz: "Zeitzone" + labelTimeAndTz: "Zeit und Zeitzone" + timezone: "Zeitzone" + showMs: "Millisekunden anzeigen" + showLabel: "Beschriftung anzeigen" + _jobQueue: + sound: "Ton abspielen" + _rss: + url: "RSS-Feed-URL" + refreshIntervalSec: "Aktualisierungsintervall (Sekunden)" + maxEntries: "Maximale Anzahl der angezeigten Einträge" + _rssTicker: + shuffle: "Zufällige Anzeigereihenfolge" + duration: "Banner-Scrollgeschwindigkeit (in Sekunden)" + reverse: "In andere Richtung scrollen" + _birthdayFollowings: + period: "Dauer" _cw: hide: "Inhalt verbergen" show: "Inhalt anzeigen" @@ -2499,9 +2628,20 @@ _postForm: replyPlaceholder: "Dieser Notiz antworten …" quotePlaceholder: "Diese Notiz zitieren …" channelPlaceholder: "In einen Kanal senden" + showHowToUse: "Formularbeschreibung anzeigen" _howToUse: + content_title: "Dieser Text" + content_description: "Bitte geben Sie den Inhalt ein, den Sie veröffentlichen möchten." + toolbar_title: "Symbolleiste" + toolbar_description: "Sie können Dateien oder Umfragen anhängen, Anmerkungen und Hashtags festlegen sowie Emojis und Erwähnungen einfügen." + account_title: "Profilmenü" + account_description: "Du kannst das Konto wechseln, von dem du postest, und dir eine Liste der im Konto gespeicherten Entwürfe und geplanten Beiträge anzeigen lassen." visibility_title: "Sichtbarkeit" + visibility_description: "Sie können den Umfang festlegen, in dem die Notizen veröffentlicht werden." menu_title: "Menü" + menu_description: "Sie können außerdem weitere Aktionen durchführen, z. B. als Entwurf speichern, das Posten planen oder Reaktionen einstellen." + submit_title: "Senden-Button" + submit_description: "Du kannst die Notiz posten. Du kannst sie auch mit Strg + Enter / Cmd + Enter posten." _placeholders: a: "Was machst du momentan?" b: "Was ist um dich herum los?" @@ -2647,6 +2787,8 @@ _notification: youReceivedFollowRequest: "Du hast eine Follow-Anfrage erhalten" yourFollowRequestAccepted: "Deine Follow-Anfrage wurde akzeptiert" pollEnded: "Umfrageergebnisse sind verfügbar" + scheduledNotePosted: "Geplante Notiz wurde veröffentlicht" + scheduledNotePostFailed: "Veröffentlichen der geplanten Notiz fehlgeschlagen" newNote: "Neue Notiz" unreadAntennaNote: "Antenne {name}" roleAssigned: "Rolle zugewiesen" @@ -2676,6 +2818,8 @@ _notification: quote: "Zitationen" reaction: "Reaktionen" pollEnded: "Ende von Umfragen" + scheduledNotePosted: "Der geplante Beitrag wurde erfolgreich veröffentlicht." + scheduledNotePostFailed: "Der geplante Beitrag ist fehlgeschlagen." receiveFollowRequest: "Erhaltene Follow-Anfragen" followRequestAccepted: "Akzeptierte Follow-Anfragen" roleAssigned: "Rolle zugewiesen" @@ -2715,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "Ist \"Automatische Breitenanpassung\" aktiviert, wird hierfür die minimale Breite verwendet" flexible: "Automatische Breitenanpassung" enableSyncBetweenDevicesForProfiles: "Aktivieren der Synchronisierung von Profilinformationen zwischen Geräten" + showHowToUse: "Siehe dir die UI-Beschreibung an." + _howToUse: + addColumn_title: "Spalte hinzufügen" + addColumn_description: "Sie können den Spaltentyp auswählen und hinzufügen." + settings_title: "UI-Einstellungen" + settings_description: "Sie können die detaillierten Einstellungen der Deck-UI vornehmen." + switchProfile_title: "Profil wechseln" + switchProfile_description: "Das UI-Layout kann als Profil gespeichert werden, sodass du jederzeit zwischen den Profilen wechseln kannst." _columns: main: "Hauptspalte" widgets: "Widgets" @@ -2775,6 +2927,8 @@ _abuseReport: notifiedWebhook: "Zu verwendender Webhook" deleteConfirm: "Bist du sicher, dass du den Empfänger der Benachrichtigung entfernen möchtest?" _moderationLogTypes: + clearQueue: "Warteschlange leeren" + promoteQueue: "Warteschlange erneut ausführen" createRole: "Rolle erstellt" deleteRole: "Rolle gelöscht" updateRole: "Rolle aktualisiert" @@ -2832,6 +2986,7 @@ _fileViewer: url: "URL" uploadedAt: "Hochgeladen am" attachedNotes: "Zugehörige Notizen" + usage: "Nutzung" thisPageCanBeSeenFromTheAuthor: "Nur der Benutzer, der diese Datei hochgeladen hat, kann diese Seite sehen." _externalResourceInstaller: title: "Von externer Seite installieren" @@ -3084,6 +3239,7 @@ _bootErrors: otherOption1: "Client-Einstellungen und Cache löschen" otherOption2: "Einfachen Client starten" otherOption3: "Starte das Reparaturwerkzeug" + otherOption4: "Misskey im abgesicherten Modus starten" _search: searchScopeAll: "Alle" searchScopeLocal: "Lokal" @@ -3120,6 +3276,8 @@ _serverSetupWizard: doYouConnectToFediverse_description1: "Bei Anschluss an ein Netz von verteilten Servern (Fediverse) können Inhalte mit anderen Servern ausgetauscht werden." doYouConnectToFediverse_description2: "Die Verbindung mit dem Fediverse wird auch als „Föderation“ bezeichnet." youCanConfigureMoreFederationSettingsLater: "Erweiterte Einstellungen, wie z. B. die Angabe von föderierbaren Servern, können später vorgenommen werden." + remoteContentsCleaning: "Automatische Bereinigung von Remote-Inhalten" + remoteContentsCleaning_description: "Wenn Sie eine Föderation durchführen, empfangen Sie fortlaufend viele Inhalte. Wenn Sie die automatische Bereinigung aktivieren, werden Remote-Inhalte, deren bestimmter Zeitraum abgelaufen ist, automatisch vom Server gelöscht, wodurch Speicherplatz eingespart werden kann." adminInfo: "Administrator-Informationen" adminInfo_description: "Legt die Administrator-Informationen fest, die für den Empfang von Anfragen verwendet werden." adminInfo_mustBeFilled: "Dies ist auf einem offenen Server oder bei aktivierter Föderation erforderlich." @@ -3144,6 +3302,7 @@ _uploader: allowedTypes: "Hochladbare Dateitypen" tip: "Die Datei ist noch nicht hochgeladen worden. In diesem Dialog kannst du die Datei vor dem Hochladen anzeigen, umbenennen, komprimieren und zuschneiden. Wenn du fertig bist, klicke auf „Hochladen“, um den Upload zu starten." _clientPerformanceIssueTip: + title: "Wenn du das Gefühl hast, dass der Akku sich schnell entlädt." makeSureDisabledAdBlocker: "Deaktiviere deinen Adblocker" makeSureDisabledAdBlocker_description: "Adblocker können die Leistung beeinträchtigen; vergewissere dich, ob in deinem Betriebssystem, Browser oder deinen Add-ons Adblocker aktiviert sind." makeSureDisabledCustomCss: "Benutzerdefiniertes CSS deaktivieren" @@ -3163,10 +3322,14 @@ _watermarkEditor: driveFileTypeWarnDescription: "Bilddatei auswählen" title: "Wasserzeichen bearbeiten" cover: "Alles bedecken" + repeat: "Wiederholen" + preserveBoundingRect: "So einstellen, dass beim Drehen nichts herausragt" opacity: "Transparenz" scale: "Größe" text: "Text" + qr: "QR-Code" position: "Position" + margin: "Abstand" type: "Art" image: "Bilder" advanced: "Fortgeschritten" @@ -3175,35 +3338,71 @@ _watermarkEditor: stripeWidth: "Linienbreite" stripeFrequency: "Linienanzahl" polkadot: "Punktmuster" + checker: "Prüfer" polkadotMainDotOpacity: "Deckkraft des Hauptpunktes" polkadotMainDotRadius: "Größe des Hauptpunktes" polkadotSubDotOpacity: "Deckkraft des Unterpunktes" polkadotSubDotRadius: "Größe des Unterpunktes" polkadotSubDotDivisions: "Anzahl der Unterpunkte" + leaveBlankToAccountUrl: "Wenn Sie es leer lassen, wird das Profilbild des Kontos verwendet." + failedToLoadImage: "Bild konnte nicht geladen werden" _imageEffector: title: "Effekte" addEffect: "Effekte hinzufügen" discardChangesConfirm: "Änderungen verwerfen und beenden?" + failedToLoadImage: "Bild konnte nicht geladen werden" _fxs: chromaticAberration: "Chromatische Abweichung" glitch: "Glitch" mirror: "Spiegeln" invert: "Farben umkehren" grayscale: "Schwarzweiß" + blur: "Verwischen" + pixelate: "Verpixeln" colorAdjust: "Farbkorrektur" colorClamp: "Farbkomprimierung" colorClampAdvanced: "Farbkomprimierung (erweitert)" distort: "Verzerrung" + threshold: "inarisierun" + zoomLines: "Konzentrationslinien" stripe: "Streifen" polkadot: "Punktmuster" + checker: "Prüfer" + blockNoise: "Blockrauschen" + tearing: "Tearing" + fill: "Ausfüllen" _fxProps: angle: "Winkel" scale: "Größe" size: "Größe" + radius: "Radius" + samples: "Stichprobengröße" offset: "Position" color: "Farbe" opacity: "Transparenz" + normalize: "Normalisierung" + amount: "Menge" lightness: "Erhellen" + contrast: "Kontrast" + hue: "Farbton" + brightness: "Helligkeit" + saturation: "Sättigung" + max: "Maximum" + min: "Minimum" + direction: "Richtung" + phase: "Sättigung" + frequency: "Häufigkeit" + strength: "Stärke" + glitchChannelShift: "Verschiebung" + seed: "Seed-Wert" + redComponent: "Rot-Anteil" + greenComponent: "Grün-Anteil" + blueComponent: "Blau-Anteil" + threshold: "Schwellenwert" + centerX: "Zentrum X" + centerY: "Zentrum Y" + zoomLinesMaskSize: "Mitteldurchmesser" + circle: "Kreisförmig" drafts: "Entwurf" _drafts: select: "Entwurf auswählen" @@ -3214,10 +3413,27 @@ _drafts: noDrafts: "Keine Entwürfe" replyTo: "Antwort an {user}" quoteOf: "Zitat von {user}s Notiz" + postTo: "Beitrag im {channel}" saveToDraft: "Als Entwurf speichern" restoreFromDraft: "Aus Entwurf wiederherstellen" restore: "Wiederherstellen" listDrafts: "Liste der Entwürfe" + schedule: "Beitragsplanung" + listScheduledNotes: "Liste der geplanten Beiträge" + cancelSchedule: "Reservierung stornieren" +qr: "QR-Code" _qr: showTabTitle: "Anzeigeart" + readTabTitle: "Auslesen" + shareTitle: "{name} {acct}" + shareText: "Bitte folge mir im Fediverse!" + chooseCamera: "Kamera auswählen" + cannotToggleFlash: "Blitzauswahl nicht möglich" + turnOnFlash: "Blitz einschalten" + turnOffFlash: "Blitz ausschalten" + startQr: "QR-Code-Leser starten" + stopQr: "QR-Code-Leser stoppen" + noQrCodeFound: "QR-Code wurde nicht gefunden" + scanFile: "Gerätebilder scannen" raw: "Text" + mfm: "MFM" diff --git a/locales/en-US.yml b/locales/en-US.yml index 22e9d6eeb9..a9729b2ce3 100644 --- a/locales/en-US.yml +++ b/locales/en-US.yml @@ -543,6 +543,7 @@ regenerate: "Regenerate" fontSize: "Font size" mediaListWithOneImageAppearance: "Height of media lists with one image only" limitTo: "Limit to {x}" +showMediaListByGridInWideArea: "Display the media list in a grid when the screen width is wide" noFollowRequests: "You don't have any pending follow requests" openImageInNewTab: "Open images in new tab" dashboard: "Dashboard" @@ -1406,6 +1407,7 @@ youAreAdmin: "You are admin" frame: "Frame" presets: "Preset" zeroPadding: "Zero padding" +nothingToConfigure: "No configurable options available" _imageEditing: _vars: caption: "File caption" @@ -1550,6 +1552,9 @@ _settings: showPageTabBarBottom: "Show page tab bar at the bottom" emojiPaletteBanner: "You can register presets as palettes to display prominently in the emoji picker or customize the appearance of the picker." enableAnimatedImages: "Enable animated images" + settingsPersistence_title: "Persistence of Settings" + settingsPersistence_description1: "Enabling setting persistence prevents configuration information from being lost." + settingsPersistence_description2: "It may not be possible to enable this depending on the environment." _chat: showSenderName: "Show sender's name" sendOnEnter: "Press Enter to send" @@ -2541,6 +2546,44 @@ _widgets: clicker: "Clicker" birthdayFollowings: "Today's Birthdays" chat: "Chat with user" +_widgetOptions: + showHeader: "Show header" + transparent: "Make background transparent" + height: "Height" + _button: + colored: "Colored" + _clock: + size: "Size" + thickness: "Needle thickness" + thicknessThin: "Thin" + thicknessMedium: "Normal" + thicknessThick: "Thick" + graduations: "Dial markings" + graduationDots: "Dot" + graduationArabic: "Arabic numbers" + fadeGraduations: "Fade the scale" + sAnimation: "Second hand animation" + sAnimationElastic: "Real" + sAnimationEaseOut: "Smooth" + twentyFour: "24 Hour Format" + labelTime: "Time" + labelTz: "Timezone" + labelTimeAndTz: "Time and time zone" + timezone: "Timezone" + showMs: "Show Miliseconds" + showLabel: "Show Label" + _jobQueue: + sound: "Play Sounds" + _rss: + url: "RSS Feed Url" + refreshIntervalSec: "Update interval (in seconds)" + maxEntries: "Maximum number of items to display" + _rssTicker: + shuffle: "Random display order" + duration: "Banner scroll speed (in seconds)" + reverse: "Scroll in the opposite direction" + _birthdayFollowings: + period: "Duration" _cw: hide: "Hide" show: "Show content" @@ -2816,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "Minimum width will be used for this when the \"Auto-adjust width\" option is enabled" flexible: "Auto-adjust width" enableSyncBetweenDevicesForProfiles: "Enable profile information sync between devices" + showHowToUse: "" + _howToUse: + addColumn_title: "Add column" + addColumn_description: "You can select and add column types." + settings_title: "UI Settings" + settings_description: "You can configure detailed settings for the deck UI." + switchProfile_title: "Profile Switching" + switchProfile_description: "You can save UI layouts as profiles and switch between them at any time." _columns: main: "Main" widgets: "Widgets" @@ -3299,7 +3350,6 @@ _imageEffector: title: "Effects" addEffect: "Add Effects" discardChangesConfirm: "Are you sure you want to leave? You have unsaved changes." - nothingToConfigure: "No configurable options available" failedToLoadImage: "Failed to load image" _fxs: chromaticAberration: "Chromatic Aberration" @@ -3351,11 +3401,7 @@ _imageEffector: threshold: "Threshold" centerX: "Center X" centerY: "Center Y" - zoomLinesSmoothing: "Smoothing" - zoomLinesSmoothingDescription: "Smoothing and zoom line width cannot be used together." - zoomLinesThreshold: "Zoom line width" zoomLinesMaskSize: "Center diameter" - zoomLinesBlack: "Make black" circle: "Circular" drafts: "Drafts" _drafts: diff --git a/locales/es-ES.yml b/locales/es-ES.yml index dddfa4d57b..72b7892128 100644 --- a/locales/es-ES.yml +++ b/locales/es-ES.yml @@ -543,6 +543,7 @@ regenerate: "Regenerar" fontSize: "Tamaño de la letra" mediaListWithOneImageAppearance: "Altura de la lista de medios con una sola imagen." limitTo: "{x} hasta un máximo de" +showMediaListByGridInWideArea: "Cuando el ancho de la pantalla sea grande, muestra la lista de multimedia uno al lado del otro." noFollowRequests: "No hay solicitudes de seguimiento" openImageInNewTab: "Abrir imagen en nueva pestaña" dashboard: "Panel de control" @@ -1406,6 +1407,7 @@ youAreAdmin: "Eres administrador." frame: "Marco" presets: "Predefinido" zeroPadding: "Relleno cero" +nothingToConfigure: "No hay nada que configurar" _imageEditing: _vars: caption: "Título del archivo" @@ -1550,6 +1552,9 @@ _settings: showPageTabBarBottom: "Mostrar la barra de pestañas de la página en la parte inferior." emojiPaletteBanner: "Puedes registrar ajustes preestablecidos como paletas para que se muestren permanentemente en el selector de emojis, o personalizar el método de visualización del selector." enableAnimatedImages: "Habilitar imágenes animadas" + settingsPersistence_title: "Persistencia de la configuración" + settingsPersistence_description1: "Habilitar la persistencia de la configuración evita que se pierda la información de configuración." + settingsPersistence_description2: "Es posible que no se pueda habilitar esta función dependiendo del entorno." _chat: showSenderName: "Mostrar el nombre del remitente" sendOnEnter: "Intro para enviar" @@ -1670,9 +1675,9 @@ _initialTutorial: title: "El concepto de Línea de tiempo" description1: "Misskey proporciona múltiples líneas de tiempo basadas en su uso (algunas pueden no estar disponibles dependiendo de las políticas de la instancia)." home: "Puedes ver los posts de las cuentas que sigues." - local: "Puedes ver los posts de todos los usuarios de este servidor." + local: "Puedes ver los posts de todos los usuarios de este servidor (también llamado instancia)." social: "Se ven los posts de la línea de tiempo de inicio junto con los de la línea de tiempo local." - global: "Puedes ver notas de todos los servidores conectados." + global: "Puedes ver notas de todos los servidores (instancias) conectados." description2: "Puedes cambiar la línea de tiempo en la parte superior de la pantalla cuando quieras." description3: "Además, hay listas de líneas de tiempo y listas de canales. Para más detalle, por favor visita este enlace: {link}" _postNote: @@ -1682,14 +1687,14 @@ _initialTutorial: description: "Puedes limitar quién puede ver tu nota." public: "Tu nota será visible para todos los usuarios." home: "Publicar solo en la línea de tiempo de Inicio. La nota se verá en tu perfil, la verán tus seguidores y también cuando sea renotada." - followers: "Visible solo para seguidores. Sólo tus seguidores podrán ver la nota, y no podrá ser renotada por otras personas." + followers: "Visible solo para seguidores. Solo tus seguidores podrán ver la nota, y no podrá ser renotada por otras personas." direct: "Visible sólo para usuarios específicos, y el destinatario será notificado. Puede usarse como alternativa a la mensajería directa." doNotSendConfidencialOnDirect1: "¡Ten cuidado cuando vayas a enviar información sensible!" doNotSendConfidencialOnDirect2: "Los administradores del servidor, también llamado instancia, pueden leer lo que escribes. Ten cuidado cuando envíes información sensible en notas directas en servidores o instancias no confiables." localOnly: "Publicando con esta opción seleccionada, la nota no se federará hacia otros servidores. Los usuarios de otros servidores no podrán ver estas notas directamente, sin importar los ajustes seleccionados más arriba." _cw: title: "Alerta de contenido (CW)" - description: "En lugar de mostrarse el contenido de la nota, se mostrará lo que escribas en el campo \"comentarios\". Pulsando en \"leer más\" desplegará el contenido de la nota." + description: "En lugar de mostrarse el contenido de la nota, se mostrará lo que escribas en el campo \"comentarios\". Pulsando en \"Ver más\" desplegará el contenido de la nota." _exampleNote: cw: "¡Esto te hará tener hambre!" note: "Acabo de comerme un donut de chocolate glaseado 🍩😋" @@ -2207,7 +2212,7 @@ _registry: key: "Clave" keys: "Clave" domain: "Dominio" - createKey: "Crear una llave" + createKey: "Crear una clave" _aboutMisskey: about: "Misskey es un software de código abierto, desarrollado por syuilo desde el 2014" contributors: "Principales colaboradores" @@ -2541,6 +2546,44 @@ _widgets: clicker: "Cliqueador" birthdayFollowings: "Hoy cumplen años" chat: "Chatear" +_widgetOptions: + showHeader: "Mostrar encabezados" + transparent: "Hacer fondo transparente" + height: "Altura" + _button: + colored: "Color" + _clock: + size: "Tamaño" + thickness: "Grosor de la aguja" + thicknessThin: "Delgada" + thicknessMedium: "Normal" + thicknessThick: "Gruesa" + graduations: "Marcas del dial" + graduationDots: "Puntos" + graduationArabic: "Números decimales" + fadeGraduations: "Desvanecer la escala" + sAnimation: "Animación de la manecilla de los segundos" + sAnimationElastic: "Real" + sAnimationEaseOut: "Suave" + twentyFour: "Formato 24 horas" + labelTime: "Hora" + labelTz: "Zona horaria" + labelTimeAndTz: "Hora y zona horaria" + timezone: "Zona horaria" + showMs: "Mostrar milisegundos" + showLabel: "Mostrar etiqueta" + _jobQueue: + sound: "Reproducir sonido" + _rss: + url: "URL del canal RSS" + refreshIntervalSec: "Intervalo de actualización (En segundos)" + maxEntries: "Número máximo de elementos a mostrar" + _rssTicker: + shuffle: "Orden de visualización aleatorio" + duration: "Velocidad de desplazamiento del baner (En segundos)" + reverse: "Desplázate en la dirección opuesta." + _birthdayFollowings: + period: "Duración" _cw: hide: "Ocultar" show: "Ver más" @@ -2816,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "Se usará el ancho mínimo cuando la opción \"Autoajustar ancho\" esté habilitada" flexible: "Autoajustar ancho" enableSyncBetweenDevicesForProfiles: "Activar la sincronización de la información de perfiles entre dispositivos." + showHowToUse: "Ver la descripción de la interfaz de usuario" + _howToUse: + addColumn_title: "Añadir columna" + addColumn_description: "Puede seleccionar y añadir tipos de columnas." + settings_title: "Configuración de la interfaz de usuario" + settings_description: "Puedes configurar la interfaz de usuario en detalle." + switchProfile_title: "Cambiar de perfil" + switchProfile_description: "Puedes guardar diseños de interfaz de usuario como perfiles y cambiar entre ellos en cualquier momento." _columns: main: "Principal" widgets: "Widgets" @@ -3145,8 +3196,8 @@ _selfXssPrevention: description2: "Si no entiendes que estás pegando exactamente, %cdetente ahora mismo y cierra esta ventana" description3: "Para más información visita esto {link}" _followRequest: - recieved: "Petición de seguimiento recibida" - sent: "Petición de seguimiento enviada" + recieved: "Solicitud de seguimiento recibida" + sent: "Solicitud de seguimiento enviada" _remoteLookupErrors: _federationNotAllowed: title: "Incapaz de comunicarse con este servidor." @@ -3299,7 +3350,6 @@ _imageEffector: title: "Efecto" addEffect: "Añadir Efecto" discardChangesConfirm: "¿Ignorar cambios y salir?" - nothingToConfigure: "No hay opciones configurables disponibles." failedToLoadImage: "Error al cargar la imagen" _fxs: chromaticAberration: "Aberración Cromática" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "Umbral" centerX: "Centrar X" centerY: "Centrar Y" - zoomLinesSmoothing: "Suavizado" - zoomLinesSmoothingDescription: "El suavizado y el ancho de línea de zoom no se pueden utilizar juntos." - zoomLinesThreshold: "Ancho de línea del zoom" + density: "Densidad" + zoomLinesOutlineThickness: "Grosor del borde" zoomLinesMaskSize: "Diámetro del centro" - zoomLinesBlack: "Cambiar color de las líneas de impacto a negro." circle: "Círculo" drafts: "Borrador" _drafts: diff --git a/locales/fr-FR.yml b/locales/fr-FR.yml index 5b3c8b75cb..63b8f3bb55 100644 --- a/locales/fr-FR.yml +++ b/locales/fr-FR.yml @@ -5,11 +5,12 @@ introMisskey: "Bienvenue ! Misskey est un service de microblogage décentralis poweredByMisskeyDescription: "{name} est l'un des services propulsés par la plateforme ouverte Misskey (appelée \"instance Misskey\")." monthAndDay: "{day}/{month}" search: "Rechercher" +reset: "Réinitialiser" notifications: "Notifications" username: "Nom d’utilisateur·rice" password: "Mot de passe" initialPasswordForSetup: "Mot de passe initial pour la configuration" -initialPasswordIsIncorrect: "Mot de passe initial pour la configuration est incorrecte" +initialPasswordIsIncorrect: "Le mot de passe initial pour la configuration est incorrect" initialPasswordForSetupDescription: "Utilisez le mot de passe que vous avez entré pour le fichier de configuration si vous avez installé Misskey vous-même.\nSi vous utilisez un service d'hébergement Misskey, utilisez le mot de passe fourni.\nSi vous n'avez pas défini de mot de passe, laissez le champ vide pour continuer." forgotPassword: "Mot de passe oublié" fetchingAsApObject: "Récupération depuis le fédiverse …" @@ -48,6 +49,7 @@ pin: "Épingler sur le profil" unpin: "Désépingler" copyContent: "Copier le contenu" copyLink: "Copier le lien" +copyRemoteLink: "Copier le lien de la note" copyLinkRenote: "Copier le lien de la renote" delete: "Supprimer" deleteAndEdit: "Supprimer et réécrire" @@ -62,8 +64,8 @@ copyNoteId: "Copier l'identifiant de la note" copyFileId: "Copier l'identifiant du fichier" copyFolderId: "Copier l'identifiant du dossier" copyProfileUrl: "Copier l'URL du profil" -searchUser: "Chercher un·e utilisateur·rice" -searchThisUsersNotes: "Cherchez les notes de cet·te utilisateur·rice" +searchUser: "Chercher un utilisateur" +searchThisUsersNotes: "Cherchez les notes de cet utilisateur" reply: "Répondre" loadMore: "Afficher plus …" showMore: "Voir plus" @@ -81,6 +83,8 @@ files: "Fichiers" download: "Télécharger" driveFileDeleteConfirm: "Êtes-vous sûr·e de vouloir supprimer le fichier « {name} » ? Les notes avec ce fichier joint seront aussi supprimées." unfollowConfirm: "Désirez-vous vous désabonner de {name} ?" +cancelFollowRequestConfirm: "Est-te vous sur de vouloir annuler la demande de suivi de {name} ?" +rejectFollowRequestConfirm: "Refuser la demande de suivi de {name} ?" exportRequested: "Vous avez demandé une exportation. L’opération pourrait prendre un peu de temps. Une fois terminée, le fichier sera ajouté au Drive." importRequested: "Vous avez initié un import. Cela pourrait prendre un peu de temps." lists: "Listes" @@ -118,6 +122,8 @@ cantReRenote: "Impossible de renoter une Renote." quote: "Citer" inChannelRenote: "Renoter dans le canal" inChannelQuote: "Citer dans le canal" +renoteToChannel: "Renoter sur le canal" +renoteToOtherChannel: "Renoter sur un autre canal" pinnedNote: "Note épinglée" pinned: "Épingler sur le profil" you: "Vous" @@ -212,6 +218,7 @@ blockThisInstance: "Bloquer cette instance" silenceThisInstance: "Mettre cette instance en sourdine" operations: "Opérations" software: "Logiciel" +softwareName: "Nom du logiciel" version: "Version" metadata: "Métadonnées" withNFiles: "{n} fichier(s)" @@ -231,6 +238,9 @@ blockedInstances: "Instances bloquées" blockedInstancesDescription: "Listez les instances que vous désirez bloquer, une par ligne. Ces instances ne seront plus en capacité d'interagir avec votre instance." silencedInstances: "Instances mises en sourdine" silencedInstancesDescription: "Énumérer les noms d'hôte des instances à mettre en sourdine. Tous les comptes des instances énumérées seront traités comme mis en sourdine, ne peuvent faire que des demandes de suivi et ne peuvent pas mentionner les comptes locaux s'ils ne sont pas suivis. Cela n'affectera pas les instances bloquées." +mediaSilencedInstances: "Médias silencieux sur ces instances" +mediaSilencedInstancesDescription: "Liste des noms de serveurs où vous voulez que les médias soient silencieux, séparés par un retour à la ligne.\nTous les comptes des instances listées seront considérés comme sensibles, et ne peuvent pas utilisés d'émojis personnalisés. Ceci n'affectera pas les serveurs bloquées." +federationAllowedHosts: "Serveurs qui autorisent la fédération" muteAndBlock: "Masqué·e·s / Bloqué·e·s" mutedUsers: "Utilisateur·rice·s en sourdine" blockedUsers: "Utilisateur·rice·s bloqué·e·s" @@ -2005,6 +2015,14 @@ _widgets: _userList: chooseList: "Sélectionner une liste" birthdayFollowings: "Utilisateurs qui fêtent l'anniversaire aujourd'hui" +_widgetOptions: + height: "Hauteur" + _button: + colored: "Coloré" + _clock: + size: "Taille" + _birthdayFollowings: + period: "Durée" _cw: hide: "Masquer" show: "Afficher le contenu" diff --git a/locales/id-ID.yml b/locales/id-ID.yml index 9afa457ebd..dbb5d63da6 100644 --- a/locales/id-ID.yml +++ b/locales/id-ID.yml @@ -2209,6 +2209,14 @@ _widgets: clicker: "Pengeklik" birthdayFollowings: "Pengguna yang merayakan hari ulang tahunnya hari ini" chat: "Obrolan pengguna" +_widgetOptions: + height: "Tinggi" + _button: + colored: "Diwarnai" + _clock: + size: "Ukuran" + _birthdayFollowings: + period: "Durasi" _cw: hide: "Sembunyikan" show: "Lihat konten" diff --git a/locales/it-IT.yml b/locales/it-IT.yml index 3b918e9c9f..2401bd84aa 100644 --- a/locales/it-IT.yml +++ b/locales/it-IT.yml @@ -127,7 +127,7 @@ renoteToOtherChannel: "Rinota a un altro canale" pinnedNote: "Nota in primo piano" pinned: "Fissa sul profilo" you: "Tu" -clickToShow: "Contenuto occultato, cliccare solo se si intende vedere" +clickToShow: "Media nascosto, cliccare solo se si intende vedere" sensitive: "Esplicito" add: "Aggiungi" reaction: "Reazioni" @@ -543,6 +543,7 @@ regenerate: "Generare di nuovo" fontSize: "Dimensione carattere" mediaListWithOneImageAppearance: "Altezza dell'elenco media con una sola immagine " limitTo: "Limita a {x}" +showMediaListByGridInWideArea: "Quando la larghezza dello schermo è ampia, mostra i media affiancati" noFollowRequests: "Non ci sono richieste di relazione" openImageInNewTab: "Apri le immagini in un nuovo tab" dashboard: "Pannello di controllo" @@ -556,7 +557,7 @@ clientSettings: "Impostazioni client" accountSettings: "Impostazioni profilo" promotion: "Promossa" promote: "Pubblicizza" -numberOfDays: "Numero di giorni" +numberOfDays: "" hideThisNote: "Nasconda la nota" showFeaturedNotesInTimeline: "Mostrare le note di tendenza nella tua timeline" objectStorage: "Storage S3" @@ -613,7 +614,7 @@ descendingOrder: "Diminuisce" scratchpad: "ScratchPad" scratchpadDescription: "Lo Scratchpad offre un ambiente per esperimenti di AiScript. È possibile scrivere, eseguire e confermare i risultati dell'interazione del codice con Misskey." uiInspector: "UI Inspector" -uiInspectorDescription: "Puoi visualizzare un elenco di elementi UI presenti in memoria. I componenti dell'interfaccia utente vengono generati dalle funzioni Ui:C:." +uiInspectorDescription: "Puoi visualizzare un elenco di elementi grafici presenti in memoria. I componenti dell'interfaccia grafica vengono generati dalle funzioni Ui:C:." output: "Output" script: "Script" disablePagesScript: "Disabilitare AiScript nelle pagine" @@ -701,7 +702,7 @@ hardWordMuteDescription: "Ignora le Note con la parola o la regola specificata. regexpError: "errore regex" regexpErrorDescription: "Si è verificato un errore nell'espressione regolare alla riga {line} della parola muta {tab}:" instanceMute: "Silenziare l'istanza" -userSaysSomething: "{name} ha detto qualcosa" +userSaysSomething: "{name} ha scritto qualcosa" userSaysSomethingAbout: "{name} ha anNotato qualcosa su \"{word}\"" makeActive: "Attiva" display: "Visualizza" @@ -1406,6 +1407,7 @@ youAreAdmin: "Sei un amministratore" frame: "Cornice" presets: "Preimpostato" zeroPadding: "Al vivo" +nothingToConfigure: "Niente da configurare" _imageEditing: _vars: caption: "Didascalia dell'immagine" @@ -1550,6 +1552,9 @@ _settings: showPageTabBarBottom: "Visualizza le schede della pagina nella parte inferiore" emojiPaletteBanner: "Puoi salvare i le emoji predefinite da appuntare in alto nel raccoglitore emoji come tavolozza e personalizzare in che modo visualizzare il raccoglitore." enableAnimatedImages: "Attivare le immagini animate" + settingsPersistence_title: "Configurazione persistente" + settingsPersistence_description1: "Attivando le impostazioni persistenti si può evitare di riconfigurare il client successivamente." + settingsPersistence_description2: "Potrebbe non essere possibile attivare, dipende dall'ambiente." _chat: showSenderName: "Mostra il nome del mittente" sendOnEnter: "Invio spedisce" @@ -1737,7 +1742,7 @@ _serverSettings: thisSettingWillAutomaticallyOffWhenModeratorsInactive: "Per prevenire SPAM, questa impostazione verrà disattivata automaticamente, se non si rileva alcuna attività di moderazione durante un certo periodo di tempo." deliverSuspendedSoftware: "Software fuori produzione" deliverSuspendedSoftwareDescription: "A causa di vulnerabilità o altri motivi, puoi interrompere la distribuzione di un software da un server specificandone il nome e la versione. Le informazioni sono fornite dall'altro server e l'autenticità non è garantita. Puoi indicare un intervallo di versione semantica, ma specificando >= 2024.3.1 non verranno incluse le versioni personalizzate come ad esempio 2024.3.1-custom.0, pertanto ti consigliamo di specificare una versione come >= 2024.3.1-0." - singleUserMode: "Modalità utente singolo" + singleUserMode: "Modalità utenza singola" singleUserMode_description: "Se sei l'unica persona a utilizzare questo server, l'abilitazione di questa modalità ottimizzerà le prestazioni." signToActivityPubGet: "Firma delle richieste GET" signToActivityPubGet_description: "Normalmente questa opzione dovrebbe essere abilitata. Se si verificano problemi con la comunicazione federata, disabilitarla potrebbe migliorare la situazione, ma d'altro canto potrebbe rendere impossibile la comunicazione, a seconda del server." @@ -2066,7 +2071,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" + mentionMax: "" canInvite: "Generare codici di invito all'istanza" inviteLimit: "Limite di codici invito" inviteLimitCycle: "Intervallo di emissione del codice di invito" @@ -2395,59 +2400,59 @@ _2fa: 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" - "read:blocks": "Visualizza i profili bloccati" - "write:blocks": "Gestisci i profili bloccati" - "read:drive": "Apri il Drive" - "write:drive": "Gestisci il Drive" - "read:favorites": "Visualizza i tuoi preferiti" - "write:favorites": "Gestisci i tuoi preferiti" - "read:following": "Vedi le informazioni di follow" - "write:following": "Aggiungere e togliere Following" - "read:messaging": "Visualizzare la chat" - "write:messaging": "Gestire la chat" - "read:mutes": "Vedi i profili silenziati" - "write:mutes": "Gestione dei profili silenziati" - "write:notes": "Creare / Eliminare note" - "read:notifications": "Visualizzare notifiche" - "write:notifications": "Gestione delle notifiche" - "read:reactions": "Vedi reazioni" - "write:reactions": "Gestione delle reazioni" + "read:account": "Vedere le informazioni sul profilo" + "write:account": "Modificare le informazioni sul profilo" + "read:blocks": "Vedere i profili bloccati" + "write:blocks": "Gestire il blocco profili" + "read:drive": "Leggere file nel Drive" + "write:drive": "Gestire file nel Drive" + "read:favorites": "Vedere le Note Preferite" + "write:favorites": "Gestire Note Preferite" + "read:following": "Vedere i Following" + "write:following": "Gestire i Following" + "read:messaging": "Vedere Messaggi Privati" + "write:messaging": "Modificare Messaggi Privati" + "read:mutes": "Vedere profili silenziati" + "write:mutes": "Gestire profili silenziati" + "write:notes": "Gestire le Note" + "read:notifications": "Vedere le notifiche" + "write:notifications": "Gestire le notifiche" + "read:reactions": "Vedere le reazioni" + "write:reactions": "Gestire le reazioni" "write:votes": "Votare" - "read:pages": "Visualizzare pagine" - "write:pages": "Gestire pagine" - "read:page-likes": "Visualizzare i \"Mi piace\" di pagine" - "write:page-likes": "Gestire i \"Mi piace\" di pagine" + "read:pages": "Vedere le pagine" + "write:pages": "Gestire le pagine" + "read:page-likes": "Vedere le Pagine piaciute" + "write:page-likes": "Modificare le Pagine piaciute" "read:user-groups": "Vedere i gruppi di utenti" "write:user-groups": "Gestire i gruppi di utenti" - "read:channels": "Visualizza canali" - "write:channels": "Gestione dei canali" - "read:gallery": "Visualizza la galleria." - "write:gallery": "Gestione della galleria" - "read:gallery-likes": "Visualizza i contenuti della galleria." - "write:gallery-likes": "Manipolazione dei \"Mi piace\" della galleria." - "read:flash": "Visualizza Play" - "write:flash": "Modifica Play" - "read:flash-likes": "Visualizza lista di Play piaciuti" - "write:flash-likes": "Modifica lista di Play piaciuti" - "read:admin:abuse-user-reports": "Mostra i report dai profili utente" - "write:admin:delete-account": "Elimina l'account utente" - "write:admin:delete-all-files-of-a-user": "Elimina i file dell'account utente" - "read:admin:index-stats": "Visualizza informazioni sugli indici del database" - "read:admin:table-stats": "Visualizza informazioni sulle tabelle del database" - "read:admin:user-ips": "Visualizza indirizzi IP degli account" - "read:admin:meta": "Visualizza i metadati dell'istanza" - "write:admin:reset-password": "Ripristina la password dell'account utente" - "write:admin:resolve-abuse-user-report": "Risolvere le segnalazioni dagli account utente" + "read:channels": "Vedere i canali" + "write:channels": "Gestire i canali" + "read:gallery": "Vedere le gallerie" + "write:gallery": "Gestire le gallerie" + "read:gallery-likes": "Vedere le Gallerie piaciute" + "write:gallery-likes": "Gestire le Gallerie piaciute" + "read:flash": "Vedere i Play" + "write:flash": "Gestire i Play" + "read:flash-likes": "Vedere la lista di Play piaciuti" + "write:flash-likes": "Modificare la lista di Play piaciuti" + "read:admin:abuse-user-reports": "Vedere le segnalazioni" + "write:admin:delete-account": "Eliminare profili" + "write:admin:delete-all-files-of-a-user": "Eliminare file dal Drive dei profili" + "read:admin:index-stats": "Vedere gli indici del database" + "read:admin:table-stats": "Vedere le statistiche database" + "read:admin:user-ips": "Vedere gli indirizzi IP dei profili" + "read:admin:meta": "Vedere i metadati dell'istanza" + "write:admin:reset-password": "Ripristinare la password del profilo" + "write:admin:resolve-abuse-user-report": "Risolvere le segnalazioni" "write:admin:send-email": "Spedire email" "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-user": "Vedere le informazioni private dei profili" "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" - "write:admin:unsuspend-user": "Togliere la sospensione ai profili" + "write:admin:unsuspend-user": "Rimuovere la sospensione ai profili" "write:admin:meta": "Modificare i metadati dell'istanza" "write:admin:user-note": "Scrivere annotazioni di moderazione" "write:admin:roles": "Gestire i ruoli" @@ -2475,11 +2480,11 @@ _permissions: "read:admin:ad": "Vedere i banner pubblicitari" "write:invite-codes": "Creare codici di invito" "read:invite-codes": "Vedere i codici di invito" - "write:clip-favorite": "Impostare Clip preferite" + "write:clip-favorite": "Modificare Clip preferite" "read:clip-favorite": "Vedere Clip preferite" "read:federation": "Vedere la federazione" "write:report-abuse": "Inviare segnalazioni" - "write:chat": "Gestire la chat" + "write:chat": "Modificare Messaggi Privati" "read:chat": "Visualizzare le chat" _auth: shareAccessTitle: "Permessi dell'applicazione" @@ -2528,19 +2533,57 @@ _widgets: instanceCloud: "Nuvola di federazione" postForm: "Finestra di pubblicazione" slideshow: "Diapositive" - button: "Pulsante" + button: "Bottone" onlineUsers: "Persone attive adesso" jobQueue: "Coda di lavoro" serverMetric: "Statistiche server" aiscript: "Console AiScript" aiscriptApp: "App AiScript" aichan: "Mascotte Ai" - userList: "Elenco utenti" + userList: "Lista profili" _userList: chooseList: "Seleziona una lista" clicker: "Cliccheria" birthdayFollowings: "Compleanni del giorno" - chat: "Chatta con questa persona" + chat: "Messaggi diretti" +_widgetOptions: + showHeader: "Mostra la testata" + transparent: "Sfondo trasparente" + height: "Altezza" + _button: + colored: "Colorato" + _clock: + size: "Dimensioni" + thickness: "Spessore lancette" + thicknessThin: "Sottili" + thicknessMedium: "Medie" + thicknessThick: "Larghe" + graduations: "Quadrante" + graduationDots: "Punti" + graduationArabic: "Numeri" + fadeGraduations: "Sfumatura" + sAnimation: "Animazione dei secondi" + sAnimationElastic: "Realistica" + sAnimationEaseOut: "Morbida" + twentyFour: "Formato 24 ore" + labelTime: "Orario" + labelTz: "Fuso orario" + labelTimeAndTz: "Orario e fuso orario" + timezone: "Fuso orario" + showMs: "Millisecondi visibili" + showLabel: "Etichetta visibile" + _jobQueue: + sound: "Emetti un suono" + _rss: + url: "URL del Feed RSS" + refreshIntervalSec: "Intervallo di aggiornamento (in secondi)" + maxEntries: "Quantità massima visualizzabile" + _rssTicker: + shuffle: "Ordine casuale" + duration: "Velocità di scorrimento del ticker (in secondi)" + reverse: "Direzione inversa" + _birthdayFollowings: + period: "Durata" _cw: hide: "Nascondere" show: "Continua la lettura..." @@ -2618,7 +2661,7 @@ _profile: metadataContent: "Contenuto" changeAvatar: "Modifica immagine profilo" changeBanner: "Cambia intestazione" - verifiedLinkDescription: "Puoi verificare il tuo profilo mostrando una icona. Devi inserire la URL alla pagina che contiene un link al tuo profilo.\nPer verificare il profilo tramite la spunta di conferma, devi inserire la url alla pagina che contiene un link al tuo profilo Misskey. Deve avere attributo rel='me'." + verifiedLinkDescription: "Come avere i collegamenti verificati: inserisci la URL ad una pagina che contiene un collegamento al tuo profilo.\nVedrai una spunta di conferma se, in quella pagina, il collegamento al tuo profilo Misskey ha attributo rel='me'." avatarDecorationMax: "Puoi aggiungere fino a {max} decorazioni." followedMessage: "Messaggio, quando qualcuno ti segue" followedMessageDescription: "Puoi impostare un breve messaggio da mostrare agli altri profili quando ti seguono." @@ -2738,7 +2781,7 @@ _notification: fileUploaded: "File caricato correttamente" youGotMention: "{name} ti ha menzionato" youGotReply: "{name} ti ha risposto" - youGotQuote: "{name} ha citato la tua Nota e ha detto" + youGotQuote: "{name} ha scritto citando la tua Nota" youRenoted: "{name} ha rinotato" youWereFollowed: "Follower aggiuntivo" youReceivedFollowRequest: "Hai ricevuto una richiesta di follow" @@ -2764,7 +2807,7 @@ _notification: exportOfXCompleted: "Abbiamo completato l'esportazione di {x}" login: "Autenticazione avvenuta" createToken: "È stato creato un token di accesso" - createTokenDescription: "In caso contrario, eliminare il token di accesso tramite ({text})." + createTokenDescription: "Se non ne sai nulla, elimina il token di accesso: {text}." _types: all: "Tutte" note: "Nuove Note" @@ -2816,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "Se \"larghezza flessibile\" è abilitato, questa diventa la larghezza minima" flexible: "Larghezza flessibile" enableSyncBetweenDevicesForProfiles: "Abilita la sincronizzazione delle informazioni profilo tra dispositivi" + showHowToUse: "Guarda la spiegazione dell'interfaccia grafica" + _howToUse: + addColumn_title: "Aggiungere colonne" + addColumn_description: "Puoi selezionare un tipo di colonna e aggiungerlo." + settings_title: "Configurazione interfaccia grafica" + settings_description: "Puoi personalizzare i dettagli dell'interfaccia grafica." + switchProfile_title: "Selettore profilo" + switchProfile_description: "Puoi salvare la disposizione dell'interfaccia grafica nel tuo profilo, affinché cambi con comodità." _columns: main: "Principale" widgets: "Riquadri" @@ -3067,7 +3118,7 @@ _contextMenu: title: "Menu contestuale" app: "Applicazione" appWithShift: "Applicazione Shift+Tasto" - native: "Interfaccia utente del browser" + native: "Interfaccia grafica del browser" _gridComponent: _error: requiredValue: "Campo obbligatorio" @@ -3299,7 +3350,6 @@ _imageEffector: title: "Effetto" addEffect: "Aggiungi effetto" discardChangesConfirm: "Scarta le modifiche ed esci?" - nothingToConfigure: "Nessuna impostazione configurabile." failedToLoadImage: "Impossibile caricare l'immagine" _fxs: chromaticAberration: "Aberrazione cromatica" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "Soglia" centerX: "Centro orizzontale" centerY: "Centro verticale" - zoomLinesSmoothing: "Levigatura" - zoomLinesSmoothingDescription: "Non si possono usare insieme la levigatura e la larghezza della linea centrale." - zoomLinesThreshold: "Limite delle linee zoom" + density: "Densità" + zoomLinesOutlineThickness: "Spessore del bordo" zoomLinesMaskSize: "Ampiezza del diametro" - zoomLinesBlack: "Bande nere" circle: "Circolare" drafts: "Bozze" _drafts: diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index 569ee445c5..c673dbb621 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -546,6 +546,7 @@ regenerate: "再生成" fontSize: "フォントサイズ" mediaListWithOneImageAppearance: "画像が1枚のみのメディアリストの高さ" limitTo: "{x}を上限に" +showMediaListByGridInWideArea: "画面幅が広いときはメディアリストを横並びで表示する" noFollowRequests: "フォロー申請はありません" openImageInNewTab: "画像を新しいタブで開く" dashboard: "ダッシュボード" @@ -1411,6 +1412,7 @@ frame: "フレーム" presets: "プリセット" zeroPadding: "ゼロ埋め" muteConfirm: "ミュートしますか?" +nothingToConfigure: "設定項目はありません" _imageEditing: _vars: @@ -1562,6 +1564,9 @@ _settings: showPageTabBarBottom: "ページのタブバーを下部に表示" emojiPaletteBanner: "絵文字ピッカーに固定表示するプリセットをパレットとして登録したり、ピッカーの表示方法をカスタマイズしたりできます。" enableAnimatedImages: "アニメーション画像を有効にする" + settingsPersistence_title: "設定の永続化" + settingsPersistence_description1: "設定の永続化を有効にすると、設定情報が失われるのを防止できます。" + settingsPersistence_description2: "環境によっては有効化できない場合があります。" _chat: showSenderName: "送信者の名前を表示" @@ -2601,9 +2606,48 @@ _widgets: _userList: chooseList: "リストを選択" clicker: "クリッカー" - birthdayFollowings: "今日誕生日のユーザー" + birthdayFollowings: "もうすぐ誕生日のユーザー" chat: "ダイレクトメッセージ" +_widgetOptions: + showHeader: "ヘッダーを表示" + transparent: "背景を透明にする" + height: "高さ" + _button: + colored: "色付き" + _clock: + size: "サイズ" + thickness: "針の太さ" + thicknessThin: "細い" + thicknessMedium: "普通" + thicknessThick: "太い" + graduations: "文字盤の目盛り" + graduationDots: "ドット" + graduationArabic: "アラビア数字" + fadeGraduations: "目盛りをフェード" + sAnimation: "秒針のアニメーション" + sAnimationElastic: "リアル" + sAnimationEaseOut: "滑らか" + twentyFour: "24時間表示" + labelTime: "時刻" + labelTz: "タイムゾーン" + labelTimeAndTz: "時刻とタイムゾーン" + timezone: "タイムゾーン" + showMs: "ミリ秒を表示" + showLabel: "ラベルを表示" + _jobQueue: + sound: "音を鳴らす" + _rss: + url: "RSSフィードのURL" + refreshIntervalSec: "更新間隔(秒)" + maxEntries: "最大表示件数" + _rssTicker: + shuffle: "表示順をシャッフル" + duration: "ティッカーのスクロール速度(秒)" + reverse: "逆方向にスクロール" + _birthdayFollowings: + period: "期間" + _cw: hide: "隠す" show: "もっと見る" @@ -2895,6 +2939,15 @@ _deck: usedAsMinWidthWhenFlexible: "「幅を自動調整」が有効の場合、これが幅の最小値となります" flexible: "幅を自動調整" enableSyncBetweenDevicesForProfiles: "プロファイル情報のデバイス間同期を有効にする" + showHowToUse: "UIの説明を見る" + + _howToUse: + addColumn_title: "カラム追加" + addColumn_description: "カラムの種類を選んで追加できます。" + settings_title: "UI設定" + settings_description: "デッキUIの詳細設定を行えます。" + switchProfile_title: "プロファイル切り替え" + switchProfile_description: "UIのレイアウトをプロファイルとして保存し、いつでも切り替えられるようにできます。" _columns: main: "メイン" @@ -3411,7 +3464,6 @@ _imageEffector: title: "エフェクト" addEffect: "エフェクトを追加" discardChangesConfirm: "変更を破棄して終了しますか?" - nothingToConfigure: "設定項目はありません" failedToLoadImage: "画像の読み込みに失敗しました" _fxs: @@ -3465,11 +3517,9 @@ _imageEffector: threshold: "しきい値" centerX: "中心X" centerY: "中心Y" - zoomLinesSmoothing: "スムージング" - zoomLinesSmoothingDescription: "スムージングと集中線の幅の設定は併用できません。" - zoomLinesThreshold: "集中線の幅" + density: "密度" + zoomLinesOutlineThickness: "線の影の太さ" zoomLinesMaskSize: "中心径" - zoomLinesBlack: "黒色にする" circle: "円形" drafts: "下書き" diff --git a/locales/ja-KS.yml b/locales/ja-KS.yml index 694965c03f..4a2cc3a9b8 100644 --- a/locales/ja-KS.yml +++ b/locales/ja-KS.yml @@ -2378,6 +2378,15 @@ _widgets: clicker: "クリッカー" birthdayFollowings: "今日誕生日のツレ" chat: "チャットしよか" +_widgetOptions: + showHeader: "ヘッダー出す" + height: "高さ" + _button: + colored: "色付き" + _clock: + size: "大きさ" + _birthdayFollowings: + period: "期間" _cw: hide: "隠す" show: "続き見して!" diff --git a/locales/ko-KR.yml b/locales/ko-KR.yml index 5a70bffeef..52da6d071a 100644 --- a/locales/ko-KR.yml +++ b/locales/ko-KR.yml @@ -543,6 +543,7 @@ regenerate: "재생성" fontSize: "글자 크기" mediaListWithOneImageAppearance: "이미지가 1개 뿐인 미디어 목록의 높이" limitTo: "{x}로 제한" +showMediaListByGridInWideArea: "화면 폭이 넓을 때는 미디어 목록을 가로로 표시하기" noFollowRequests: "처리되지 않은 팔로우 요청이 없습니다" openImageInNewTab: "새 탭에서 이미지 열기" dashboard: "대시보드" @@ -1334,7 +1335,7 @@ markAsSensitiveConfirm: "이 미디어를 민감한 미디어로 설정하시겠 unmarkAsSensitiveConfirm: "이 미디어의 민감한 미디어 지정을 해제하시겠습니까?" preferences: "환경설정" accessibility: "접근성" -preferencesProfile: "설정 프로필" +preferencesProfile: "설정 프로파일" copyPreferenceId: "설정한 ID를 복사" resetToDefaultValue: "기본값으로 되돌리기" overrideByAccount: "계정으로 덮어쓰기" @@ -1347,7 +1348,7 @@ preferenceSyncConflictTitle: "서버에 설정값이 존재합니다." preferenceSyncConflictText: "동기화를 활성화 한 항목의 설정 값은 서버에 저장되지만, 해당 항목은 이미 서버에 설정 값이 저장되어져 있습니다. 어느 쪽의 설정 값을 덮어씌울까요?" preferenceSyncConflictChoiceMerge: "병합" preferenceSyncConflictChoiceServer: "서버 설정값" -preferenceSyncConflictChoiceDevice: "장치 설정값" +preferenceSyncConflictChoiceDevice: "장치 설정 값" preferenceSyncConflictChoiceCancel: "동기화 취소" paste: "붙여넣기" emojiPalette: "이모지 팔레트" @@ -1406,6 +1407,7 @@ youAreAdmin: "당신은 관리자입니다." frame: "프레임" presets: "프리셋" zeroPadding: "0으로 채우기" +nothingToConfigure: "설정 항목이 없습니다." _imageEditing: _vars: caption: "파일 설명" @@ -1464,17 +1466,17 @@ _chat: newMessage: "새로운 메시지" individualChat: "개인 대화" individualChat_description: "특정 유저와 일대일 채팅을 할 수 있습니다." - roomChat: "룸 채팅" + roomChat: "그룹 채팅" roomChat_description: "여러 명이 함께 채팅할 수 있습니다.\n또한, 개인 채팅을 허용하지 않은 유저와도 상대방이 수락하면 채팅을 할 수 있습니다." - createRoom: "룸을 생성" + createRoom: "방 만들기" inviteUserToChat: "유저를 초대하여 채팅을 시작하세요" - yourRooms: "생성한 룸" - joiningRooms: "참가 중인 룸" + yourRooms: "만들어진 방" + joiningRooms: "참가 중인 방" invitations: "초대" noInvitations: "초대장이 없습니다" history: "이력" noHistory: "기록이 없습니다" - noRooms: "룸이 없습니다" + noRooms: "방이 없습니다" inviteUser: "유저를 초대" sentInvitations: "초대를 보내기" join: "참여" @@ -1485,14 +1487,14 @@ _chat: home: "홈" send: "전송" newline: "줄바꿈" - muteThisRoom: "이 룸을 뮤트" - deleteRoom: "룸을 삭제" + muteThisRoom: "이 방을 뮤트하기" + deleteRoom: "방을 삭제하기" chatNotAvailableForThisAccountOrServer: "이 서버 또는 이 계정에서 채팅이 활성화되어 있지 않습니다." chatIsReadOnlyForThisAccountOrServer: "이 서버 또는 이 계정에서 채팅은 읽기 전용입니다. 새로 쓰거나 채팅 룸을 만들거나 참가할 수 없습니다." chatNotAvailableInOtherAccount: "상대방 계정에서 채팅 기능을 사용할 수 없는 상태입니다." cannotChatWithTheUser: "이 유저와 채팅을 시작할 수 없습니다" cannotChatWithTheUser_description: "채팅을 사용할 수 없는 상태이거나 상대방이 채팅을 열지 않은 상태입니다." - youAreNotAMemberOfThisRoomButInvited: "당신은 이 룸의 참가자가 아닙니다만 초대 신청을 받으셨습니다. 참가하려면 초대를 수락해주십시오." + youAreNotAMemberOfThisRoomButInvited: "이 방의 참가자가 아니지만 초대를 받았습니다. 참가하려면 초대를 수락하세요." doYouAcceptInvitation: "초대를 수락하시겠습니까?" chatWithThisUser: "채팅하기" thisUserAllowsChatOnlyFromFollowers: "이 유저는 팔로워만 채팅을 할 수 있습니다." @@ -1550,15 +1552,18 @@ _settings: showPageTabBarBottom: "페이지의 탭 바를 아래쪽에 표시" emojiPaletteBanner: "이모티콘 선택기에 고정 표시되는 프리셋을 팔레트로 등록하거나 선택기의 표시 방법을 커스터마이징할 수 있습니다." enableAnimatedImages: "애니메이션 이미지 활성화" + settingsPersistence_title: "설정 영구화" + settingsPersistence_description1: "설정 영구화를 활성화하면 설정 정보를 잃어버리는 것을 방지할 수 있습니다." + settingsPersistence_description2: "환경에 따라 활성화되지 않을 수 있습니다." _chat: showSenderName: "발신자 이름 표시" sendOnEnter: "엔터로 보내기" _preferencesProfile: - profileName: "프로필 이름" + profileName: "프로파일 이름" profileNameDescription: "이 디바이스를 식별할 이름을 설정해 주세요." profileNameDescription2: "예: '메인PC', '스마트폰' 등" manageProfiles: "프로파일 관리" - shareSameProfileBetweenDevicesIsNotRecommended: "여러 장치에서 동일한 프로필을 공유하는 것은 권장하지 않습니다." + shareSameProfileBetweenDevicesIsNotRecommended: "여러 장치에서 같은 프로파일을 공유하는 것은 권장하지 않습니다." useSyncBetweenDevicesOptionIfYouWantToSyncSetting: "여러 장치에서 동기화하고 싶은 설정 항목이 있는 경우에는 개별로 '여러 장치에서 동기화' 옵션을 활성화해 주십시오." _preferencesBackup: autoBackup: "자동 백업" @@ -1566,7 +1571,7 @@ _preferencesBackup: noBackupsFoundTitle: "백업을 찾을 수 없습니다" noBackupsFoundDescription: "자동으로 생성된 백업은 찾을 수 없었지만, 수동으로 백업 파일을 저장한 경우 해당 파일을 가져와 복원할 수 있습니다." selectBackupToRestore: "복원할 백업을 선택하세요" - youNeedToNameYourProfileToEnableAutoBackup: "자동 백업을 활성화하려면 프로필 이름을 설정해야 합니다." + youNeedToNameYourProfileToEnableAutoBackup: "자동 백업을 활성화하려면 프로파일 이름을 설정해야 합니다." autoPreferencesBackupIsNotEnabledForThisDevice: "이 장치에서 설정 자동 백업이 활성화되어 있지 않습니다." backupFound: "설정 백업이 발견되었습니다" forceBackup: "설정 강제 백업" @@ -2539,8 +2544,46 @@ _widgets: _userList: chooseList: "리스트 선택" clicker: "클리커" - birthdayFollowings: "오늘이 생일인 유저" + birthdayFollowings: "곧 생일인 사용자" chat: "채팅하기" +_widgetOptions: + showHeader: "해더를 표시" + transparent: "배경을 투명하게 설정" + height: "높이" + _button: + colored: "색 입히기" + _clock: + size: "크기" + thickness: "시곗바늘의 두께" + thicknessThin: "얇게" + thicknessMedium: "보통" + thicknessThick: "굵게" + graduations: "문자반의 눈금" + graduationDots: "도트" + graduationArabic: "아라비아 숫자" + fadeGraduations: "눈금 페이드" + sAnimation: "초침 애니메이션" + sAnimationElastic: "사실적으로" + sAnimationEaseOut: "매끄럽게" + twentyFour: "24시간 표시" + labelTime: "시각" + labelTz: "시간대" + labelTimeAndTz: "시각과 시간대" + timezone: "시간대" + showMs: "밀리초 표시" + showLabel: "레이블 표시" + _jobQueue: + sound: "소리 재생" + _rss: + url: "RSS 필드의 URL" + refreshIntervalSec: "갱신 간격(초)" + maxEntries: "최대 표시 건수" + _rssTicker: + shuffle: "표시 순서 셔플" + duration: "티커 스크롤 속도(초)" + reverse: "역방향으로 스크롤" + _birthdayFollowings: + period: "기간" _cw: hide: "숨기기" show: "더 보기" @@ -2749,7 +2792,7 @@ _notification: newNote: "새 게시물" unreadAntennaNote: "안테나 {name}" roleAssigned: "역할이 부여 되었습니다." - chatRoomInvitationReceived: "채팅 룸에 초대받았습니다" + chatRoomInvitationReceived: "채팅방에 초대되었습니다" emptyPushNotificationMessage: "푸시 알림이 갱신되었습니다" achievementEarned: "도전 과제를 달성했습니다" testNotification: "알림 테스트" @@ -2780,7 +2823,7 @@ _notification: receiveFollowRequest: "팔로우 요청을 받았을 때" followRequestAccepted: "팔로우 요청이 승인되었을 때" roleAssigned: "역할이 부여됨" - chatRoomInvitationReceived: "채팅 룸에 초대받음" + chatRoomInvitationReceived: "채팅방에 초대됨" achievementEarned: "도전 과제 획득" exportCompleted: "추출을 성공함" login: "로그인" @@ -2815,7 +2858,15 @@ _deck: useSimpleUiForNonRootPages: "루트 이외의 페이지로 접속한 경우 UI 간략화하기" usedAsMinWidthWhenFlexible: "'폭 자동 조정'이 활성화된 경우 최소 폭으로 사용됩니다" flexible: "폭 자동 조정" - enableSyncBetweenDevicesForProfiles: "프로파일 정보의 디바이스 간 동기화를 활성화" + enableSyncBetweenDevicesForProfiles: "프로파일 정보의 장치 간 동기화를 활성화" + showHowToUse: "UI 설명 보기" + _howToUse: + addColumn_title: "칼럼 추가" + addColumn_description: "칼럼의 종류를 선택해 추가할 수 있습니다." + settings_title: "UI 설정" + settings_description: "덱 UI의 상세 설정을 할 수 있습니다." + switchProfile_title: "프로파일 전환" + switchProfile_description: "UI의 레이아웃을 프로파일로 저장하고 언제든지 전환할 수 있습니다." _columns: main: "메인" widgets: "위젯" @@ -2926,7 +2977,7 @@ _moderationLogTypes: deletePage: "페이지를 삭제" deleteFlash: "Play를 삭제" deleteGalleryPost: "갤러리 게시물을 삭제" - deleteChatRoom: "채팅 룸 삭제" + deleteChatRoom: "채팅방 삭제하기" updateProxyAccountDescription: "프록시 계정의 설명 업데이트" _fileViewer: title: "파일 상세" @@ -3299,7 +3350,6 @@ _imageEffector: title: "이펙트" addEffect: "이펙트를 추가" discardChangesConfirm: "변경을 취소하고 종료하시겠습니까?" - nothingToConfigure: "설정 항목이 없습니다." failedToLoadImage: "이미지 로딩에 실패했습니다." _fxs: chromaticAberration: "색수차" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "한계 값" centerX: "X축 중심" centerY: "Y축 중심" - zoomLinesSmoothing: "다듬기" - zoomLinesSmoothingDescription: "다듬기와 집중선 폭 설정은 같이 쓸 수 없습니다." - zoomLinesThreshold: "집중선 폭" + density: "밀도" + zoomLinesOutlineThickness: "선 그림자의 굵기" zoomLinesMaskSize: "중앙 값" - zoomLinesBlack: "검은색으로 하기" circle: "원형" drafts: "초안" _drafts: diff --git a/locales/lo-LA.yml b/locales/lo-LA.yml index 06856867b0..7017d81733 100644 --- a/locales/lo-LA.yml +++ b/locales/lo-LA.yml @@ -431,6 +431,8 @@ _widgets: jobQueue: "ຄິວວຽກ" _userList: chooseList: "ເລືອກບັນຊີລາຍການ" +_widgetOptions: + height: "ຄວາມສູງ" _cw: show: "ໂຫຼດເພີ່ມເຕີມ" _visibility: diff --git a/locales/nl-NL.yml b/locales/nl-NL.yml index 27f782e611..32e021d1a1 100644 --- a/locales/nl-NL.yml +++ b/locales/nl-NL.yml @@ -1017,6 +1017,8 @@ _widgets: jobQueue: "Job Queue" _userList: chooseList: "Kies een lijst." +_widgetOptions: + height: "Hoogte" _cw: show: "Laad meer" _visibility: diff --git a/locales/no-NO.yml b/locales/no-NO.yml index 6f60223342..7bf3f387b8 100644 --- a/locales/no-NO.yml +++ b/locales/no-NO.yml @@ -639,6 +639,10 @@ _widgets: userList: "Brukerliste" _userList: chooseList: "Velg liste" +_widgetOptions: + height: "Høyde" + _clock: + size: "Størrelse" _cw: hide: "Skjul" show: "Vis mer" diff --git a/locales/pl-PL.yml b/locales/pl-PL.yml index 18dd43e938..34540239fb 100644 --- a/locales/pl-PL.yml +++ b/locales/pl-PL.yml @@ -1361,6 +1361,14 @@ _widgets: _userList: chooseList: "Wybierz listę" clicker: "Clicker" +_widgetOptions: + height: "Wysokość" + _button: + colored: "Kolorowe" + _clock: + size: "Rozmiar" + _birthdayFollowings: + period: "Czas trwania" _cw: hide: "Ukryj" show: "Załaduj więcej" diff --git a/locales/pt-PT.yml b/locales/pt-PT.yml index 2ee5b06ec2..0fba19df40 100644 --- a/locales/pt-PT.yml +++ b/locales/pt-PT.yml @@ -2489,6 +2489,15 @@ _widgets: clicker: "Clicker" birthdayFollowings: "Usuários de aniversário hoje" chat: "Conversar com usuário" +_widgetOptions: + showHeader: "Exibir cabeçalho" + height: "Altura" + _button: + colored: "Colorido" + _clock: + size: "Tamanho" + _birthdayFollowings: + period: "Duração" _cw: hide: "Esconder" show: "Carregar mais" @@ -3230,7 +3239,6 @@ _imageEffector: title: "Efeitos" addEffect: "Adicionar efeitos" discardChangesConfirm: "Tem certeza que deseja sair? Há mudanças não salvas." - nothingToConfigure: "Não há nada para configurar" _fxs: chromaticAberration: "Aberração cromática" glitch: "Glitch" @@ -3281,11 +3289,7 @@ _imageEffector: threshold: "Limiar" centerX: "Centralizar X" centerY: "Centralizar Y" - zoomLinesSmoothing: "Suavização" - zoomLinesSmoothingDescription: "Suavização e largura das linhas de zoom não podem ser utilizados simultaneamente." - zoomLinesThreshold: "Largura das linhas de zoom" zoomLinesMaskSize: "Diâmetro do centro" - zoomLinesBlack: "Linhas pretas" circle: "Circular" drafts: "Rascunhos" _drafts: diff --git a/locales/ro-RO.yml b/locales/ro-RO.yml index d1ff2f1040..bf352b45c2 100644 --- a/locales/ro-RO.yml +++ b/locales/ro-RO.yml @@ -1301,6 +1301,12 @@ _widgets: jobQueue: "coada de job-uri" _userList: chooseList: "Selectează o listă" +_widgetOptions: + height: "Înălţime" + _button: + colored: "Colorat" + _clock: + size: "Dimensiune" _cw: show: "Incarcă mai mult" _visibility: diff --git a/locales/ru-RU.yml b/locales/ru-RU.yml index c77487c41b..f14a0019e9 100644 --- a/locales/ru-RU.yml +++ b/locales/ru-RU.yml @@ -83,6 +83,8 @@ files: "Файлы" download: "Скачать" driveFileDeleteConfirm: "Удалить файл «{name}»? Заметки с ним также будут удалены." unfollowConfirm: "Отписаться от {name} ?" +cancelFollowRequestConfirm: "Вы уверены, что хотите отменить запрос на подписку пользователю {name}?" +rejectFollowRequestConfirm: "Отклонить запрос на подписку от {name}?" exportRequested: "Вы запросили экспорт. Это может занять некоторое время. Результат будет добавлен на «Диск»." importRequested: "Вы запросили импорт. Это может занять некоторое время." lists: "Списки" @@ -199,7 +201,7 @@ searchWith: "Найденное «{q}»" youHaveNoLists: "У вас нет ни одного списка" followConfirm: "Подписаться на {name}?" proxyAccount: "Учётная запись прокси" -proxyAccountDescription: "Учетная запись прокси предназначена служить подписчиком на пользователей с других сайтов. Например, если пользователь добавит кого-то с другого сайта а список, деятельность того не отобразится, пока никто с этого же сайта не подписан на него. Чтобы это стало возможным, на него подписывается прокси." +proxyAccountDescription: "Учетная запись прокси предназначена служить подписчиком на пользователей с других сайтов. Например: если пользователь добавит кого-то с другого сайта в список, то деятельность того не отобразится, пока никто с этого же сайта не подписан на него. Чтобы это стало возможным, на него подписывается прокси." host: "Хост" selectSelf: "Выбрать себя" selectUser: "Выберите пользователя" @@ -302,6 +304,7 @@ uploadFromUrlMayTakeTime: "Загрузка может занять некото uploadNFiles: "Загрузить {n} файл" explore: "Обзор" messageRead: "Прочитали" +readAllChatMessages: "Отметить прочитанным" noMoreHistory: "История закончилась" startChat: "Начать чат" nUsersRead: "Прочитали {n}" @@ -328,11 +331,13 @@ dark: "Тёмный" lightThemes: "Светлые темы" darkThemes: "Тёмные темы" syncDeviceDarkMode: "Синхронизировать с тёмной темой системы" +switchDarkModeManuallyWhenSyncEnabledConfirm: "Включена функция \"{x}\". Отключить синхронизацию, чтобы переключать режим вручную?" drive: "Диск" fileName: "Имя файла" selectFile: "Выберите файл" selectFiles: "Выберите файлы" selectFolder: "Выберите папку" +unselectFolder: "Снять выбор" selectFolders: "Выберите папки" fileNotSelected: "Файл не выбран" renameFile: "Переименовать файл" @@ -345,6 +350,7 @@ addFile: "Добавить файл" showFile: "Посмотреть файл" emptyDrive: "Диск пуст" emptyFolder: "Папка пуста" +dropHereToUpload: "Переместите файл сюда" unableToDelete: "Удаление невозможно" inputNewFileName: "Введите имя нового файла" inputNewDescription: "Введите новую подпись" @@ -458,7 +464,7 @@ moderator: "Модератор" moderation: "Модерация" moderationNote: "Примечания модератора" moderationNoteDescription: "Вы можете заполнять заметки, которые будут доступны только модераторам." -addModerationNote: "" +addModerationNote: "Оставить заметку" moderationLogs: "Журнал модерации" nUsersMentioned: "Упомянуло пользователей: {n}" securityKeyAndPasskey: "Ключ безопасности и парольная фраза" @@ -602,7 +608,7 @@ installedDate: "Дата установки" lastUsedDate: "Дата использования" state: "Состояние" sort: "Сортировать" -ascendingOrder: "по возрастанию" +ascendingOrder: "По возрастанию" descendingOrder: "По убыванию" scratchpad: "Когтеточка" scratchpadDescription: "«Когтеточка» — это место для опытов с AiScript. Здесь можно писать программы, взаимодействующие с Misskey, запускать и смотреть что из этого получается." @@ -623,9 +629,9 @@ removeAllFollowingDescription: "Отменить все подписки с до userSuspended: "Эта учётная запись заморожена" userSilenced: "Этот пользователь был заглушен" yourAccountSuspendedTitle: "Эта учетная запись заблокирована" -yourAccountSuspendedDescription: "Эта учетная запись была заблокирована из-за нарушения условий предоставления услуг сервера. Свяжитесь с администратором, если вы хотите узнать более подробную причину. Пожалуйста, не создавайте новую учетную запись." +yourAccountSuspendedDescription: "Этот аккаунт нарушил ToS сервера, поэтому был заморожен. Свяжитесь с администратором, чтобы узнать подробности. Не пытайтесь создать новый аккаунт." tokenRevoked: "Токен недействителен" -tokenRevokedDescription: "Срок действия вашего токена входа истек. Пожалуйста, войдите снова." +tokenRevokedDescription: "Токен входа устарел. Пожалуйста, войдите снова." accountDeleted: "Учетная запись удалена" accountDeletedDescription: "Эта учетная запись удалена" menu: "Меню" @@ -684,9 +690,9 @@ smtpPort: "Порт" smtpUser: "Имя пользователя" smtpPass: "Пароль" emptyToDisableSmtpAuth: "Не заполняйте имя пользователя и пароль, чтобы отключить аутентификацию в SMTP." -smtpSecure: "Использовать SSL/TLS для SMTP-соединений" +smtpSecure: "Использовать SSL/TLS" smtpSecureInfo: "Выключите при использовании STARTTLS." -testEmail: "Проверка доставки электронной почты" +testEmail: "Отправить тестовое письмо" wordMute: "Скрытие слов" wordMuteDescription: "Сведите к минимуму записи, содержащие указанное утверждение. Нажмите на свернутую запись, чтобы отобразить ее." hardWordMute: "Строгое скрытие слов" @@ -772,6 +778,7 @@ lockedAccountInfo: "Даже если вы вручную подтверждае alwaysMarkSensitive: "Отмечать файлы как «содержимое не для всех» по умолчанию" loadRawImages: "Сразу показывать изображения в полном размере" disableShowingAnimatedImages: "Не проигрывать анимацию" +disableShowingAnimatedImages_caption: "Если анимации всё равно не работают, проверьте настройки специальных возможностей и режимы экономии заряда в браузере или системе" highlightSensitiveMedia: "Выделять содержимое не для всех" verificationEmailSent: "Вам отправлено письмо для подтверждения. Пройдите, пожалуйста, по ссылке из письма, чтобы завершить проверку." notSet: "Не настроено" @@ -779,7 +786,7 @@ emailVerified: "Адрес электронной почты подтвержд noteFavoritesCount: "Количество добавленного в избранное" pageLikesCount: "Количество понравившихся страниц" pageLikedCount: "Количество страниц, понравившихся другим" -contact: "Как связаться" +contact: "Почта для связи" useSystemFont: "Использовать шрифт, предлагаемый системой" clips: "Подборки" experimentalFeatures: "Экспериментальные функции" @@ -838,7 +845,7 @@ showingPastTimeline: "Отображается старая лента" clear: "Очистить" markAllAsRead: "Отметить всё как прочитанное" goBack: "Выход" -unlikeConfirm: "В самом деле отменить «нравится»?" +unlikeConfirm: "В самом деле убрать «нравится»?" fullView: "Полный вид" quitFullView: "Закрыть полный вид" addDescription: "Добавить описание" @@ -883,7 +890,7 @@ priority: "Приоритет" high: "Высокий" middle: "Средне" low: "Низкий" -emailNotConfiguredWarning: "Не указан адрес электронной почты" +emailNotConfiguredWarning: "Адрес почты пустует" ratio: "Соотношение" previewNoteText: "Предварительный просмотр" customCss: "Индивидуальный CSS" @@ -963,13 +970,13 @@ reflectMayTakeTime: "Изменения могут занять время дл failedToFetchAccountInformation: "Не удалось получить информацию об аккаунте" rateLimitExceeded: "Ограничение скорости превышено" cropImage: "Кадрирование" -cropImageAsk: "Нужно ли кадрировать изображение?" +cropImageAsk: "Обрезать изображение?" cropYes: "Обрезать" cropNo: "Не обрезать" file: "Файлы" recentNHours: "Последние {n} ч" recentNDays: "Последние {n} сут" -noEmailServerWarning: "Почтовый сервер не установлен " +noEmailServerWarning: "Отправка писем выключена" thereIsUnresolvedAbuseReportWarning: "Остались нерешённые жалобы" recommended: "Рекомендуем" check: "Проверить" @@ -983,7 +990,7 @@ document: "Документ" numberOfPageCache: "Количество сохранённых страниц в кэше" numberOfPageCacheDescription: "Описание количества страниц в кэше" logoutConfirm: "Вы хотите выйти из аккаунта?" -logoutWillClearClientData: "Когда вы выйдете из системы, информация о конфигурации клиента будет удалена из браузера.Чтобы иметь возможность восстановить информацию о вашей конфигурации при повторном входе в систему, пожалуйста, включите опцию автоматического резервного копирования в настройках." +logoutWillClearClientData: "Выход из аккаунта удалит настройки клиента из этого браузера. Включите автоматическое резервное копирование, чтобы иметь возможность восстановить настройки при повторном входе." lastActiveDate: "Последняя дата использования" statusbar: "Статусбар" pleaseSelect: "Пожалуйста, выберите" @@ -1002,6 +1009,7 @@ failedToUpload: "Сбой выгрузки" cannotUploadBecauseInappropriate: "Файл не может быть загружен, так как было установлено, что он может содержать неприемлемое содержимое." cannotUploadBecauseNoFreeSpace: "Файл не может быть загружен, так как не осталось места на диске" cannotUploadBecauseExceedsFileSizeLimit: "Файл не может быть загружен, так как он превышает лимит размера файла." +cannotUploadBecauseUnallowedFileType: "Формат файла не подходит" beta: "Бета" enableAutoSensitive: "Автоматическое определение содержимого не для всех" enableAutoSensitiveDescription: "Позволяет определять наличие содержимого не для всех при помощи искусственного интеллекта там, где это возможно. Даже если эту опцию отключить, она всё равно может быть включена на весь инстанс." @@ -1017,6 +1025,9 @@ pushNotificationAlreadySubscribed: "Push-уведомления уже вклю pushNotificationNotSupported: "Push-уведмления не поддерживаются инстансом или браузером" sendPushNotificationReadMessage: "Удалять push-уведомления когда сообщение или прочитано" sendPushNotificationReadMessageCaption: "На мгновение появится уведомление \"{emptyPushNotificationMessage}\". Расход заряда батареи может увеличиться " +pleaseAllowPushNotification: "Пожалуйста, разрешите уведомление в браузере от сайта" +browserPushNotificationDisabled: "Вы не дали разрешение на уведомления сайту" +browserPushNotificationDisabledDescription: "Разрешите уведомления в настройках браузера от {serverName}, чтобы включить PUSH уведомления" windowMaximize: "Развернуть" windowMinimize: "Свернуть" windowRestore: "Восстановить" @@ -1038,7 +1049,7 @@ roles: "Роли" role: "Роль" noRole: "Нет роли" normalUser: "Обычный пользователь" -undefined: "неопределён" +undefined: "неопределённо" assign: "Назначить" unassign: "Отменить назначение" color: "Цвет" @@ -1053,6 +1064,7 @@ permissionDeniedError: "Операция запрещена" permissionDeniedErrorDescription: "У этой учетной записи нет разрешения на выполнение этой операции." preset: "Шаблоны" selectFromPresets: "Выбрать из шаблонов" +custom: "Пользовательские" achievements: "Достижения" gotInvalidResponseError: "Сервер ответил ошибкой" gotInvalidResponseErrorDescription: "Сервер временно не доступен. Возможно проводятся технические работы, или сервер отключен." @@ -1091,6 +1103,7 @@ prohibitedWordsDescription2: "Разделение пробелом создаё hiddenTags: "Скрытые хештеги" hiddenTagsDescription: "Установленные теги не будут отображаться в тренде, можно установить несколько тегов." notesSearchNotAvailable: "Поиск заметок недоступен" +usersSearchNotAvailable: "Функция \"поиска пользователей\" отключена" license: "Лицензия" unfavoriteConfirm: "Удалить избранное?" myClips: "Мои подборки" @@ -1129,7 +1142,7 @@ vertical: "Вертикально" horizontal: "Горизонтально" position: "Позиция" serverRules: "Правила сервера" -pleaseConfirmBelowBeforeSignup: "Для регистрации на данном сервере, необходимо согласится с нижеследующими положениями." +pleaseConfirmBelowBeforeSignup: "Прочитайте и согласитесь с информацией ниже, чтобы продолжить" pleaseAgreeAllToContinue: "Чтобы продолжить, необходимо поставить отметки во всех полях \"согласен\"." continue: "Продолжить" preservedUsernames: "Зарезервированные имена пользователей" @@ -1178,6 +1191,9 @@ expirationDate: "Дата истечения" noExpirationDate: "Бессрочно" inviteCodeUsedAt: "Дата и время, когда был использован пригласительный код" registeredUserUsingInviteCode: "Пользователи, которые использовали пригласительный код" +waitingForMailAuth: "Подтвердите вашу электронную почту" +inviteCodeCreator: "Создатель приглашения" +usedAt: "Использовано" unused: "Неиспользованное" used: "Использован" expired: "Срок действия приглашения истёк" @@ -1186,43 +1202,59 @@ beSureToReadThisAsItIsImportant: "Это важно, поэтому, пожал iHaveReadXCarefullyAndAgree: "Я прочитал(а) и согласен(сна) с условиями \"{x}" dialog: "Диалог" icon: "Аватар" +forYou: "Для вас" currentAnnouncements: "Текущие новости" pastAnnouncements: "Предыдущие новости" youHaveUnreadAnnouncements: "У вас есть непрочитанные уведомления" +useSecurityKey: "Используйте ключ безопасности или Passkey, следуя подсказкам браузера" replies: "Ответы" renotes: "Репост" loadReplies: "Показать ответы" loadConversation: "Загрузить беседу" pinnedList: "Закреплённый список" keepScreenOn: "Держать экран включённым" +verifiedLink: "Эта ссылка принадлежит пользователю" +notifyNotes: "Оповещать о публикациях" unnotifyNotes: "Отписаться от сообщений" authentication: "Аутентификация" authenticationRequiredToContinue: "Пожалуйста, пройдите аутентификацию, чтобы продолжить" dateAndTime: "Дата и время" showRenotes: "Показывать репосты" edited: "Изменено" +notificationRecieveConfig: "Настроить оповещения" mutualFollow: "Взаимные подписки" followingOrFollower: "Подписки или подписчики" fileAttachedOnly: "Только заметки с файлами" showRepliesToOthersInTimeline: "Показывать ответы в ленте" +hideRepliesToOthersInTimeline: "Скрыть чужие ответы в ленте" showRepliesToOthersInTimelineAll: "Показывать в ленте ответы пользователей, на которых вы подписаны" hideRepliesToOthersInTimelineAll: "Скрывать в ленте ответы пользователей, на которых вы подписаны" +confirmShowRepliesAll: "Это нельзя будет отменить. Показать ответы от всех, на кого вы подписаны?" +confirmHideRepliesAll: "Это нельзя будет отменить. Скрыть ответы от всех, на кого вы подписаны?" +externalServices: "Интеграции" sourceCode: "Исходный код" sourceCodeIsNotYetProvided: "Исходный код пока не доступен. Свяжитесь с администратором, чтобы исправить эту проблему." repositoryUrl: "Ссылка на репозиторий" repositoryUrlDescription: "Если вы используете Misskey как есть (без изменений в исходном коде), введите https://github.com/misskey-dev/misskey" +repositoryUrlOrTarballRequired: "Если репозиторий закрыт, необходимо предоставить ссылку на tarball. Подробности см. в файле \".config/example.yml\"" feedback: "Обратная связь" +feedbackUrl: "Ссылка для обратной связи" +impressum: "О владельце" privacyPolicy: "Политика Конфиденциальности" privacyPolicyUrl: "Ссылка на Политику Конфиденциальности" tosAndPrivacyPolicy: "Условия использования и политика конфиденциальности" avatarDecorations: "Украшения для аватара" attach: "Прикрепить" +detach: "Открепить" detachAll: "Убрать всё" angle: "Угол" flip: "Переворот" showAvatarDecorations: "Показать украшения для аватара" +releaseToRefresh: "Отпустите, чтобы обновить" +refreshing: "Обновление..." pullDownToRefresh: "Опустите что бы обновить" useGroupedNotifications: "Отображать уведомления сгруппировано" +emailVerificationFailedError: "Не смогли подтвердить почту. Вероятно, истек срок письма" cwNotationRequired: "Если включена опция «Скрыть содержимое», необходимо написать аннотацию." doReaction: "Добавить реакцию" code: "Код" @@ -1232,34 +1264,49 @@ overwriteContentConfirm: "Текущее содержимое будет пер seasonalScreenEffect: "Эффект времени года на экране" decorate: "Украсить" addMfmFunction: "Добавить MFM" +enableQuickAddMfmFunction: "Показывать расширенный выбор MFM" bubbleGame: "BubbleGame" sfx: "Звуковые эффекты" soundWillBePlayed: "Будет воспроизведен звук" showReplay: "Показать повтор" +replay: "Ответить" endReplay: "Конец повтора" lastNDays: "Последние {n} сут" hemisphere: "Место проживания" userSaysSomethingSensitive: "Сообщение, содержит конфиденциальные файлы от {name}" enableHorizontalSwipe: "Смахните в сторону, чтобы сменить вкладки" +loading: "Загрузка" surrender: "Этот пост не может быть отменен." gameRetry: "Повторить попытку" notUsePleaseLeaveBlank: "Если не используется, оставьте пустым" +useTotp: "Включить двухэтапную проверку" +useBackupCode: "Использовать резервные коды" +launchApp: "Запустить приложение" useNativeUIForVideoAudioPlayer: "Использовать интерфейс браузера при проигрывании видео и звука" keepOriginalFilename: "Сохранять исходное имя файла" keepOriginalFilenameDescription: "Если вы выключите данную настройку, имена файлов будут автоматически заменены случайной строкой при загрузке." +noDescription: "Нет описания" alwaysConfirmFollow: "Всегда подтверждать подписку" inquiry: "Связаться" +tryAgain: "Попробуйте еще раз позже" +confirmWhenRevealingSensitiveMedia: "Спрашивать перед открытием NSFW контента" +sensitiveMediaRevealConfirm: "Возможно, это NSFW контент. Показать?" +createdLists: "Созданные списки" +createdAntennas: "Созданные антенны" fromX: "Из {x}" genEmbedCode: "Сгенерировать код для " noteOfThisUser: "Список заметок этого пользователя" clipNoteLimitExceeded: "К этому клипу больше нельзя добавить заметки" performance: "Производительность" modified: "Изменено" +discard: "Отменить" +thereAreNChanges: "Изменено: {n}" signinWithPasskey: "Войдите в систему, используя свой пароль" unknownWebAuthnKey: "Неизвестный ключ" passkeyVerificationFailed: "Ошибка проверка ключа доступа " +passkeyVerificationSucceededButPasswordlessLoginDisabled: "Проверка Passkey выполнена, но вход без пароля отключен" messageToFollower: "Сообщение подписчикам" -testCaptchaWarning: "Эта функция предназначена для тестирования CAPTCHA. Не использовать это в рабочей среде" +testCaptchaWarning: "Эта тестовая CAPTCHA. Не используйте её!" prohibitedWordsForNameOfUser: "Запрещенные слова (имя пользователя)" prohibitedWordsForNameOfUserDescription: "Если имя пользователя содержит строку из этого списка, изменение имени пользователя будет запрещено. На пользователей с правами модератора это ограничение не распространяется. Имена пользователей также проверяются путём замены всех букв в нижнем регистре" yourNameContainsProhibitedWords: "Имя, которое вы пытаетесь изменить, содержит запрещенную строку символов" @@ -1268,24 +1315,65 @@ thisContentsAreMarkedAsSigninRequiredByAuthor: "Автор сообщения у lockdown: "Доступ ограничен" pleaseSelectAccount: "Выберите свой аккаунт" availableRoles: "Доступные роли" +federationSpecified: "Сервер работает через белый список федерации. Связь с другими серверами ограничена" federationDisabled: "Федерация отключена для этого сервера. Вы не можете взаимодействовать с пользователями на других серверах." draft: "Черновик" +draftsAndScheduledNotes: "Черновики и отложенные публикации" +confirmOnReact: "Подтверждать добавление реакции" +reactAreYouSure: "Добавить {emoji}?" markAsSensitiveConfirm: "Отметить контент как чувствительный?" +unmarkAsSensitiveConfirm: "Снять пометку о NSFW контенте?" preferences: "Основное" +accessibility: "Специальные возможности" +preferencesProfile: "Настройки профиля" +copyPreferenceId: "Копировать ID настройки" resetToDefaultValue: "Сбросить настройки до стандартных" +overrideByAccount: "Переопределить этим аккаунтом" +untitled: "Без названия" +noName: "Имя не указано" +skip: "Пропустить" syncBetweenDevices: "Синхронизировать между устройствами" postForm: "Форма отправки" textCount: "Количество символов" information: "Описание" inMinutes: "мин" inDays: "сут" +schedule: "Отложить" +scheduled: "Отложено" widgets: "Виджеты" +deviceInfo: "Об устройстве" +deviceInfoDescription: "Эта информация может быть полезна при обращении в поддержку" +youAreAdmin: "Вы администратор" +frame: "Рамки" presets: "Шаблоны" +zeroPadding: "Без отступов" +nothingToConfigure: "Нечего менять" _imageEditing: _vars: + caption: "Описание файла" filename: "Имя файла" + filename_without_ext: "Имя файла без расширения" + year: "Год создания" + month: "Месяц создания" + day: "День создания" + hour: "Час создания" + minute: "Минуты создания" + second: "Секунды создания" + camera_model: "Модель камеры" + camera_lens_model: "Модель линзы" + camera_mm: "Фокусное расстояние" + camera_mm_35: "Фокусное расстояние (экв. 35 мм)" + camera_f: "Диафрагма" + camera_s: "Выдержка" + camera_iso: "ISO" + gps_lat: "Широта" + gps_long: "Долгота" _imageFrameEditor: + title: "Редактировать рамку" header: "Заголовок" + footer: "Нижняя часть" + borderThickness: "Толщина рамки" + labelThickness: "Толщина границ" font: "Шрифт" fontSerif: "Антиква (с засечками)" fontSansSerif: "Гротеск (без засечек)" @@ -1661,6 +1749,7 @@ _emailUnavailable: disposable: "Временный адрес электронной почты не принимается" mx: "Неверный почтовый сервер" smtp: "Почтовый сервер не отвечает" + banned: "Этот адрес почты недоступен" _ffVisibility: public: "Общедоступны" followers: "Показываются только подписчикам" @@ -1921,6 +2010,7 @@ _permissions: "read:gallery-likes": "Просмотр списка понравившегося в галерее" "write:gallery-likes": "Изменение списка понравившегося в галерее" "write:admin:reset-password": "Сбросить пароль пользователю" + "write:admin:send-email": "Отправить письмо" "write:chat": "Писать и удалять сообщения" _auth: shareAccessTitle: "Разрешения для приложений" @@ -1976,6 +2066,14 @@ _widgets: chooseList: "Выберите список" clicker: "Счётчик щелчков" birthdayFollowings: "Пользователи, у которых сегодня день рождения" +_widgetOptions: + height: "Высота" + _button: + colored: "Выделена цветом" + _clock: + size: "Размер" + _birthdayFollowings: + period: "Длительность" _cw: hide: "Спрятать" show: "Показать" @@ -2245,6 +2343,7 @@ _abuseReport: mail: "Электронная почта" webhook: "Вебхук" _captions: + mail: "Уведомлять модераторов по почте (только при поступлении жалоб)" webhook: "Отправить уведомление Системному Вебхуку при получении или разрешении жалоб." notifiedWebhook: "Используемый Вебхук" _moderationLogTypes: diff --git a/locales/sk-SK.yml b/locales/sk-SK.yml index 937fbdfebf..b6289f4e04 100644 --- a/locales/sk-SK.yml +++ b/locales/sk-SK.yml @@ -1232,6 +1232,14 @@ _widgets: aichan: "Ai" _userList: chooseList: "Vyberte zoznam" +_widgetOptions: + height: "Výška" + _button: + colored: "Farebné" + _clock: + size: "Veľkosť" + _birthdayFollowings: + period: "Trvanie" _cw: hide: "Skryť" show: "Zobraziť viac" diff --git a/locales/sv-SE.yml b/locales/sv-SE.yml index c0fd267546..560f4a187c 100644 --- a/locales/sv-SE.yml +++ b/locales/sv-SE.yml @@ -639,6 +639,9 @@ _widgets: jobQueue: "Jobbkö" _userList: chooseList: "Välj lista" +_widgetOptions: + _clock: + size: "Storlek" _cw: hide: "Dölj" show: "Ladda mer" diff --git a/locales/th-TH.yml b/locales/th-TH.yml index e4c30c0101..6bcff59979 100644 --- a/locales/th-TH.yml +++ b/locales/th-TH.yml @@ -83,6 +83,8 @@ files: "ไฟล์" download: "ดาวน์โหลด" driveFileDeleteConfirm: "ต้องการลบไฟล์ “{name}” ใช่ไหม? โน้ตที่แนบมากับไฟล์นี้ก็จะถูกลบไปด้วย" unfollowConfirm: "ต้องการเลิกติดตาม {name} ใช่ไหม?" +cancelFollowRequestConfirm: "ยกเลิกคำขอติดตาม {name} ใช่ไหม?" +rejectFollowRequestConfirm: "ปฏิเสธคำขอติดตามจาก {name} ใช่ไหม?" exportRequested: "คุณได้ร้องขอการส่งออก อาจใช้เวลาสักครู่ และจะถูกเพิ่มในไดรฟ์ของคุณเมื่อเสร็จสิ้นแล้ว" importRequested: "คุณได้ร้องขอการนำเข้า การดำเนินการนี้อาจใช้เวลาสักครู่" lists: "รายชื่อ" @@ -204,7 +206,7 @@ host: "โฮสต์" selectSelf: "เลือกตัวเอง" selectUser: "เลือกผู้ใช้งาน" recipient: "ผู้รับ" -annotation: "หมายเหตุประกอบ" +annotation: "ข้อความเกริ่น" federation: "สหพันธ์" instances: "เซิร์ฟเวอร์" registeredAt: "วันที่ลงทะเบียน" @@ -222,7 +224,7 @@ operations: "ดำเนินการ" software: "ซอฟต์แวร์" softwareName: "ชื่อซอฟต์แวร์" version: "เวอร์ชั่น" -metadata: "Metadata" +metadata: "เมทาเดต้า" withNFiles: "{n} ไฟล์" monitor: "มอนิเตอร์" jobQueue: "คิวงาน" @@ -302,6 +304,7 @@ uploadFromUrlMayTakeTime: "การอัปโหลดอาจใช้เ uploadNFiles: "อัปโหลด {n} ไฟล์" explore: "สำรวจ" messageRead: "อ่านแล้ว" +readAllChatMessages: "ทำเครื่องหมายใส่ข้อความทั้งหมดว่าอ่านแล้ว" noMoreHistory: "ไม่มีประวัติเพิ่มเติม" startChat: "เริ่มแชต" nUsersRead: "อ่านโดย {n}" @@ -334,6 +337,7 @@ fileName: "ชื่อไฟล์" selectFile: "เลือกไฟล์" selectFiles: "เลือกไฟล์" selectFolder: "เลือกโฟลเดอร์" +unselectFolder: "ยกเลิกการเลือกโฟลเดอร์" selectFolders: "เลือกโฟลเดอร์" fileNotSelected: "ยังไม่ได้เลือกไฟล์" renameFile: "เปลี่ยนชื่อไฟล์" @@ -346,6 +350,7 @@ addFile: "เพิ่มไฟล์" showFile: "แสดงไฟล์" emptyDrive: "ไดรฟ์ของคุณว่างเปล่านะ" emptyFolder: "โฟลเดอร์นี้ว่างเปล่า" +dropHereToUpload: "ดรอปไฟล์ลงที่นี่เพื่ออัปโหลด" unableToDelete: "ไม่สามารถลบออกได้" inputNewFileName: "ป้อนชื่อไฟล์ใหม่" inputNewDescription: "กรุณาใส่แคปชั่นใหม่" @@ -428,7 +433,7 @@ antennaKeywordsDescription: "คั่นด้วยเว้นวรรคส notifyAntenna: "แจ้งเตือนเกี่ยวกับโน้ตใหม่" withFileAntenna: "เฉพาะโน้ตที่มีไฟล์" excludeNotesInSensitiveChannel: "ไม่รวมโน้ตจากช่องเนื้อหาละเอียดอ่อน" -enableServiceworker: "เปิดใช้งานการแจ้งเตือนแบบพุชไปยังเบราว์เซอร์ของคุณ" +enableServiceworker: "เปิดใช้งานการแจ้งเตือนแบบพุชไปยังเบราว์เซอร์" antennaUsersDescription: "ระบุหนึ่งชื่อผู้ใช้ต่อบรรทัด" caseSensitive: "อักษรพิมพ์ใหญ่-พิมพ์เล็กความหมายต่างกัน" withReplies: "รวมตอบกลับ" @@ -538,6 +543,7 @@ regenerate: "สร้างอีกครั้ง" fontSize: "ขนาดตัวอักษร" mediaListWithOneImageAppearance: "ความสูงของรายการสื่อที่มีเพียงรูปเดียว" limitTo: "จำกัดไว้ที่ {x}" +showMediaListByGridInWideArea: "เมื่อหน้าจอกว้างยาวขึ้น ให้เรียงรายการสื่อเป็นแนวนอน" noFollowRequests: "คุณไม่มีคำขอติดตามที่รอดำเนินการ" openImageInNewTab: "เปิดรูปภาพในแท็บใหม่" dashboard: "หน้ากระดานหลัก" @@ -612,7 +618,7 @@ uiInspectorDescription: "คุณสามารถตรวจสอบรา output: "เอาท์พุต" script: "สคริปต์" disablePagesScript: "ปิดการใช้งาน AiScript บนเพจ" -updateRemoteUser: "อัปเดตข้อมูลผู้ใช้งานระยะไกล" +updateRemoteUser: "อัปเดตข้อมูลผู้ใช้ระยะไกล" unsetUserAvatar: "เลิกตั้งไอคอน" unsetUserAvatarConfirm: "ต้องการเลิกตั้งไอคอนประจำตัวหรือไม่?" unsetUserBanner: "เลิกตั้งแบนเนอร์" @@ -773,6 +779,7 @@ lockedAccountInfo: "แม้ว่าการอนุมัติการต alwaysMarkSensitive: "ทำเครื่องหมายว่ามีเนื้อหาละเอียดอ่อนเป็นค่าเริ่มต้น" loadRawImages: "โหลดภาพต้นฉบับแทนการแสดงภาพขนาดย่อ" disableShowingAnimatedImages: "ไม่ต้องเล่นภาพเคลื่อนไหว" +disableShowingAnimatedImages_caption: "หากภาพเคลื่อนไหวไม่เล่นแม่จะปิดตั้งค่านี้ไปแล้ว อาจเป็นกรณีที่การตั้งค่าการช่วยการเข้าถึงหรือการประหยัดพลังงาน ของเบราว์เซอร์/OS เข้าแทรกแซง" highlightSensitiveMedia: "ไฮไลท์สื่อที่มีเนื้อหาละเอียดอ่อน" verificationEmailSent: "ได้ส่งอีเมลยืนยันแล้ว กรุณาเข้าลิงก์ที่ระบุในอีเมลเพื่อทำการตั้งค่าให้เสร็จสิ้น" notSet: "ไม่ได้ตั้งค่า" @@ -887,7 +894,7 @@ low: "ต่ำ" emailNotConfiguredWarning: "ยังไม่ได้ตั้งค่าที่อยู่อีเมล" ratio: "อัตราส่วน" previewNoteText: "แสดงตัวอย่าง" -customCss: "CSS ที่กำหนดเอง" +customCss: "CSS แบบกำหนดเอง" customCssWarn: "ควรใช้การตั้งค่านี้เฉพาะต่อเมื่อคุณรู้มันใช้ทำอะไร การตั้งค่าที่ไม่เหมาะสมอาจทำให้ไคลเอ็นต์ไม่สามารถใช้งานได้อย่างถูกต้อง" global: "ทั่วโลก" squareAvatars: "แสดงไอคอนประจำตัวเป็นสี่เหลี่ยม" @@ -930,7 +937,7 @@ unmuteThread: "เลิกปิดเสียงเธรด" followingVisibility: "การมองเห็นที่เรากำลังติดตาม" followersVisibility: "การมองเห็นผู้ที่กำลังติดตามเรา" continueThread: "ดูความต่อเนื่องเธรด" -deleteAccountConfirm: "การดำเนินการนี้จะลบบัญชีของคุณอย่างถาวรเลยนะ แน่ใจหรอดำเนินการ?" +deleteAccountConfirm: "บัญชีจะถูกลบ ดำเนินการต่อใช่ไหม?" incorrectPassword: "รหัสผ่านไม่ถูกต้อง" incorrectTotp: "รหัสยืนยันตัวตนแบบใช้ครั้งเดียวที่ท่านได้ระบุมานั้น ไม่ถูกต้องหรือหมดอายุลงแล้วค่ะ" voteConfirm: "ต้องการโหวต “{choice}” ใช่ไหม?" @@ -991,7 +998,7 @@ pleaseSelect: "ตัวเลือก" reverse: "พลิก" colored: "สี" refreshInterval: "ความถี่ในการอัปเดต" -label: "ป้ายชื่อ" +label: "ป้าย" type: "รูปแบบ" speed: "ความเร็ว" slow: "ช้า" @@ -1019,6 +1026,9 @@ pushNotificationAlreadySubscribed: "การแจ้งเตือนแบ pushNotificationNotSupported: "เบราว์เซอร์หรือเซิร์ฟเวอร์ไม่รองรับการแจ้งเตือนแบบพุช" sendPushNotificationReadMessage: "ลบการแจ้งเตือนแบบพุชเมื่ออ่านการแจ้งเตือนหรือข้อความที่เกี่ยวข้องแล้ว" sendPushNotificationReadMessageCaption: "อาจทำให้อุปกรณ์ของคุณใช้พลังงานมากขึ้น" +pleaseAllowPushNotification: "โปรดอนุญาตการตั้งค่าการแจ้งเตือนของเบราว์เซอร์" +browserPushNotificationDisabled: "ขอสิทธิ์ส่งการแจ้งเตือนล้มเหลว" +browserPushNotificationDisabledDescription: "ไม่มีสิทธิ์ในการส่งการแจ้งเตือนจาก {serverName} โปรดอนุญาตการแจ้งเตือนในตั้งค่าของเบราว์เซอร์ แล้วลองอีกครั้ง" windowMaximize: "ขยายใหญ่สุด" windowMinimize: "ย่อเล็กที่สุด" windowRestore: "เลิกทำ" @@ -1099,8 +1109,8 @@ license: "ใบอนุญาต" unfavoriteConfirm: "ลบออกจากรายการโปรดแน่ใจหรอ?" myClips: "คลิปของฉัน" drivecleaner: "ทำความสะอาดไดรฟ์" -retryAllQueuesNow: "ลองเรียกใช้คิวทั้งหมดอีกครั้ง" -retryAllQueuesConfirmTitle: "ลองใหม่ทั้งหมดจริงๆหรอแน่ใจนะ?" +retryAllQueuesNow: "ลองใหม่ทุกคิวทันที" +retryAllQueuesConfirmTitle: "ลองใหม่ทันทีเลยไหม?" retryAllQueuesConfirmText: "สิ่งนี้จะเพิ่มการโหลดเซิร์ฟเวอร์ชั่วคราวนะ" enableChartsForRemoteUser: "สร้างแผนภูมิข้อมูลผู้ใช้ระยะไกล" enableChartsForFederatedInstances: "สร้างแผนภูมิของเซิร์ฟเวอร์ระยะไกล" @@ -1150,7 +1160,7 @@ initialAccountSetting: "ตั้งค่าโปรไฟล์" youFollowing: "ติดตามแล้ว" preventAiLearning: "ปฏิเสธการเรียนรู้ด้วย generative AI" preventAiLearningDescription: "ส่งคำร้องขอไม่ให้ใช้ ข้อความในโน้ตที่โพสต์, หรือเนื้อหารูปภาพ ฯลฯ ในการเรียนรู้ของเครื่อง(machine learning) / Predictive AI / Generative AI โดยการเพิ่มแฟล็ก “noai” ลง HTML-Response ให้กับเนื้อหาที่เกี่ยวข้อง แต่ทั้งนี้ ไม่ได้ป้องกัน AI จากการเรียนรู้ได้อย่างสมบูรณ์ เนื่องจากมี AI บางตัวเท่านั้นที่จะเคารพคำขอดังกล่าว" -options: "ตัวเลือกบทบาท" +options: "ตัวเลือก" specifyUser: "ผู้ใช้เฉพาะ" lookupConfirm: "ต้องการเรียกดูข้อมูลใช่ไหม?" openTagPageConfirm: "ต้องการเปิดหน้าแฮชแท็กใช่ไหม?" @@ -1169,6 +1179,7 @@ installed: "ติดตั้งแล้ว" branding: "แบรนดิ้ง" enableServerMachineStats: "เผยแพร่สถานะฮาร์ดแวร์ของเซิร์ฟเวอร์" enableIdenticonGeneration: "เปิดใช้งานผู้ใช้สร้างตัวระบุ" +showRoleBadgesOfRemoteUsers: "แสดงตราบทบาทที่มอบให้กับผู้ใช้ระยะไกล" turnOffToImprovePerformance: "การปิดส่วนนี้สามารถเพิ่มประสิทธิภาพได้" createInviteCode: "สร้างรหัสเชิญ" createWithOptions: "สร้างด้วยตัวเลือก" @@ -1247,7 +1258,7 @@ refreshing: "กำลังรีเฟรช..." pullDownToRefresh: "ดึงลงเพื่อรีเฟรช" useGroupedNotifications: "แสดงผลการแจ้งเตือนแบบกลุ่มแล้ว" emailVerificationFailedError: "เกิดปัญหาในขณะตรวจสอบอีเมล อาจเป็นไปได้ว่าลิงก์หมดอายุแล้ว" -cwNotationRequired: "หากเปิดใช้งาน “ซ่อนเนื้อหา” จะต้องระบุคำอธิบาย" +cwNotationRequired: "หากเปิดใช้งาน “ซ่อนเนื้อหา” จะต้องระบุข้อความเกริ่น" doReaction: "เพิ่มรีแอคชั่น" code: "โค้ด" reloadRequiredToApplySettings: "จำเป็นต้องมีการโหลดซ้ำเพื่อให้การตั้งค่ามีผล" @@ -1351,7 +1362,7 @@ migrateOldSettings: "ย้ายข้อมูลการตั้งค่ migrateOldSettings_description: "โดยปกติจะทำโดยอัตโนมัติ แต่หากด้วยเหตุผลบางประการที่ไม่สามารถย้ายได้สำเร็จ สามารถสั่งย้ายด้วยตนเองได้ การตั้งค่าปัจจุบันจะถูกเขียนทับ" compress: "บีบอัด" right: "ขวา" -bottom: "ภายใต้" +bottom: "ล่าง" top: "บน" embed: "ฝัง" settingsMigrating: "กำลังย้ายการตั้งค่า กรุณารอสักครู่... (สามารถย้ายด้วยตนเองภายหลังได้ที่ การตั้งค่า → อื่นๆ → ย้ายข้อมูลการตั้งค่าเก่า)" @@ -1390,17 +1401,53 @@ scheduledToPostOnX: "มีการกำหนดเวลาให้โพ schedule: "กำหนดเวลา" scheduled: "กำหนดเวลา" widgets: "วิดเจ็ต" +deviceInfo: "รายละเอียดอุปกรณ์" +deviceInfoDescription: "เมื่อต้องการรับความช่วยเหลือทางเทคนิค กรุณาระบุข้อมูลต่อไปนี้ซึ่งอาจช่วยแก้ไขปัญหาได้" +youAreAdmin: "คุณคือผู้ดูแลระบบ" +frame: "เฟรม" presets: "พรีเซ็ต" +zeroPadding: "ห่างเป็น 0" +nothingToConfigure: "ไม่มีอะไรให้ต้ังค่า" _imageEditing: _vars: + caption: "แคปชั่นของไฟล์" filename: "ชื่อไฟล์" + filename_without_ext: "ชื่อไฟล์ที่ไม่มีนามสกุล" + year: "ปีที่ถ่าย" + month: "เดือนที่ถ่าย" + day: "วันที่ถ่าย" + hour: "เวลาที่ถ่าย (ชั่วโมง)" + minute: "เวลาที่ถ่าย (นาที)" + second: "เวลาที่ถ่าย (วินาที)" + camera_model: "ชื่อกล้อง" + camera_lens_model: "ชื่อเลนส์" + camera_mm: "ความยาวโฟกัส" + camera_mm_35: "ทางยาวโฟกัส (เทียบเท่า 35 มม.)" + camera_f: "รูรับแสง" + camera_s: "ความเร็วชัตเตอร์" + camera_iso: "ความไวแสง ISO" + gps_lat: "ละติจูด" + gps_long: "ลองจิจูด" _imageFrameEditor: + title: "แก้ไขเฟรม" + tip: "สามารถตกแต่งภาพโดยการเพิ่มป้ายที่มีเฟรมหรือเมทาเดต้าได้" header: "ส่วนหัว" + footer: "ท้ายกระดาษ" + borderThickness: "ความกว้างขอบ" + labelThickness: "ความกว้างป้าย" + labelScale: "สเกลของป้าย" + centered: "จัดกึ่งกลาง" + captionMain: "แคปชั่น (ใหญ่)" + captionSub: "แคปชั่น (เล็ก)" + availableVariables: "ตัวแปรที่สามารถใช้ได้" withQrCode: "QR โค้ด" + backgroundColor: "สีพื้นหลัง" + textColor: "สีตัวอักษร" font: "แบบอักษร" fontSerif: "Serif" fontSansSerif: "Sans Serif" quitWithoutSaveConfirm: "ต้องการออกโดยไม่บันทึกหรือไม่?" + failedToLoadImage: "โหลดภาพล้มเหลว" _compression: _quality: high: "คุณภาพสูง" @@ -1503,6 +1550,11 @@ _settings: showUrlPreview: "แสดงตัวอย่าง URL" showAvailableReactionsFirstInNote: "แสดงรีแอคชั่นที่ใช้ได้ไว้หน้าสุด" showPageTabBarBottom: "แสดงแท็บบาร์ของเพจที่ด้านล่าง" + emojiPaletteBanner: "สามารถบันทึกพรีเซ็ตเป็นจานสีเพื่อตรึงไว้ในตัวจิ้มเอโมจิ หรือปรับแต่งวิธีการแสดงผลของตัวจิ้มเอโมจิได้" + enableAnimatedImages: "เปิดใช้งานภาพเคลื่อนไหว" + settingsPersistence_title: "คงสภาพการตั้งค่า" + settingsPersistence_description1: "เมื่อเปิดใช้งานการคงสภาพการตั้งค่า จะช่วยป้องกันไม่ให้ข้อมูลการตั้งค่าสูญหายได้" + settingsPersistence_description2: "แต่ในบางสภาพแวดล้อม อาจไม่สามารถเปิดใช้งานได้" _chat: showSenderName: "แสดงชื่อผู้ส่ง" sendOnEnter: "กด Enter เพื่อส่ง" @@ -1511,6 +1563,8 @@ _preferencesProfile: profileNameDescription: "กรุณาตั้งชื่อเพื่อระบุอุปกรณ์นี้" profileNameDescription2: "เช่น: “คอมเครื่องหลัก”, “มือถือ” ฯลฯ" manageProfiles: "จัดการโปรไฟล์" + shareSameProfileBetweenDevicesIsNotRecommended: "ไม่แนะนำให้ใช้โปรไฟล์เดียวกันร่วมกันบนหลายอุปกรณ์" + useSyncBetweenDevicesOptionIfYouWantToSyncSetting: "หากมีรายการตั้งค่าที่ต้องการซิงก์ระหว่างหลายอุปกรณ์ โปรดเปิดใช้งานตัวเลือก “ซิงก์ระหว่างหลายอุปกรณ์” ในอุปกรณ์นั้นๆ ด้วย" _preferencesBackup: autoBackup: "สำรองโดยอัตโนมัติ" restoreFromBackup: "คืนค่าจากข้อมูลสำรอง" @@ -1518,8 +1572,9 @@ _preferencesBackup: noBackupsFoundDescription: "ไม่พบข้อมูลสำรองที่สร้างโดยอัตโนมัติ แต่หากมีข้อมูลสำรองที่บันทึกด้วยตนเอง สามารถนำเข้ามาเพื่อกู้คืนได้" selectBackupToRestore: "กรุณาเลือกข้อมูลสำรองที่ต้องการกู้คืน" youNeedToNameYourProfileToEnableAutoBackup: "จำเป็นต้องตั้งชื่อโปรไฟล์ก่อนจึงจะเปิดใช้งานการสำรองข้อมูลอัตโนมัติได้" - autoPreferencesBackupIsNotEnabledForThisDevice: "ยังไม่ได้เปิดใช้งานการสำรองข้อมูลอัตโนมัติบนอุปกรณ์นี้" + autoPreferencesBackupIsNotEnabledForThisDevice: "ยังไม่ได้เปิดใช้งานการสำรองการตั้งค่าแบบอัตโนมัติบนอุปกรณ์นี้" backupFound: "พบข้อมูลสำรองของการตั้งค่าแล้ว" + forceBackup: "บังคับสำรองการตั้งค่า" _accountSettings: requireSigninToViewContents: "ต้องเข้าสู่ระบบเพื่อดูเนื้อหา" requireSigninToViewContentsDescription1: "กำหนดให้ต้องเข้าสู่ระบบก่อนจึงจะสามารถดูโน้ตหรือเนื้อหาทั้งหมดที่สร้างไว้ได้ ซึ่งช่วยป้องกันไม่ให้ข้อมูลถูกเก็บโดยบอตหรือ Crawler (โปรแกรมรวบรวมข้อมูล)" @@ -1587,7 +1642,7 @@ _initialAccountSetting: theseSettingsCanEditLater: "คุณสามารถเปลี่ยนการตั้งค่าเหล่านี้ได้ในภายหลังได้ตลอดเวลานะ" youCanEditMoreSettingsInSettingsPageLater: "สามารถตั้งค่าเพิ่มเติมได้ที่หน้า “การตั้งค่า” อย่าลืมไปเยี่ยมชมภายหลังด้วย" followUsers: "ลองติดตามผู้ใช้ที่สนใจเพื่อสร้างไทม์ไลน์ดูสิ" - pushNotificationDescription: "กำลังเปิดใช้งานการแจ้งเตือนแบบพุชจะช่วยให้คุณได้รับการแจ้งเตือนจาก {name} โดยตรงบนอุปกรณ์ของคุณนะ" + pushNotificationDescription: "เมื่อเปิดใช้งานการแจ้งเตือนแบบพุช จะสามารถรับการแจ้งเตือนจาก {name} บนอุปกรณ์ที่ใช้งานอยู่ได้" initialAccountSettingCompleted: "ตั้งค่าโปรไฟล์เสร็จสมบูรณ์แล้ว!" haveFun: "ขอให้สนุกกับ {name}!" youCanContinueTutorial: "คุณสามารถดำเนินการต่อด้วยบทช่วยสอนเกี่ยวกับวิธีใช้ {name} (Misskey) หรือออกจากบทช่วยสอนแล้วเริ่มใช้งานได้ทันที" @@ -1639,7 +1694,7 @@ _initialTutorial: localOnly: "การโพสต์ด้วย flag นี้จะไม่รวมโน้ตไปยังเซิร์ฟเวอร์อื่น ผู้ใช้บนเซิร์ฟเวอร์อื่นจะไม่สามารถดูโน้ตเหล่านี้ได้โดยตรง โดยไม่คำนึงถึงการตั้งค่าการแสดงผลข้างต้น" _cw: title: "คำเตือนเกี่ยวกับเนื้อหา" - description: "เนื้อหาที่เขียนใน “คำอธิบายประกอบ” จะแสดงแทนเนื้อหาหลัก ต้องคลิก “ดูเพิ่มเติม” เพื่อให้เนื้อหาหลักแสดง" + description: "เนื้อหาที่เขียนใน “ข้อความเกริ่น” จะแสดงแทนเนื้อหาหลัก ต้องกด “ดูเพิ่มเติม” เพื่อให้เนื้อหาหลักแสดง" _exampleNote: cw: " ห้ามดู ระวังหิว" note: "เพิ่งไปกินโดนัทเคลือบช็อคโกแลตมา 🍩😋" @@ -1991,7 +2046,7 @@ _role: isConditionalRole: "นี่คือบทบาทที่มีเงื่อนไข" isPublic: "ทำให้บทบาทเปิดเผยต่อสาธารณะ" descriptionOfIsPublic: "บทบาทจะปรากฏบนโปรไฟล์ของผู้ใช้และเปิดเผยต่อสาธารณะ (ทุกคนสามารถเห็นได้ว่าผู้ใช้รายนี้มีบทบาทนี้)" - options: "ตัวเลือกบทบาท" + options: "ตัวเลือก" policies: "นโยบาย" baseRole: "แม่แบบบทบาท" useBaseValue: "ใช้ตามแม่แบบบทบาท" @@ -2025,6 +2080,7 @@ _role: canManageAvatarDecorations: "จัดการตกแต่งอวตาร" driveCapacity: "ความจุของไดรฟ์" maxFileSize: "ขนาดไฟล์สูงสุดที่สามารถอัปโหลดได้" + maxFileSize_caption: "รีเวิร์สพร็อกซี, CDN และคอมโพเนนต์หน้าบ้านอื่นๆ อาจมีค่าการตั้งค่าของตนเอง" alwaysMarkNsfw: "ทำเครื่องหมายไฟล์ว่าเป็น NSFW เสมอ" canUpdateBioMedia: "อนุญาตให้เปลี่ยนไอคอนประจำตัวและแบนเนอร์" pinMax: "จํานวนสูงสุดของโน้ตที่ปักหมุดไว้" @@ -2386,7 +2442,7 @@ _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": "ส่งอีเมล" @@ -2397,7 +2453,7 @@ _permissions: "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": "ดูบทบาท" @@ -2443,6 +2499,7 @@ _auth: scopeUser: "กำลังดำเนินการในฐานะผู้ใช้ต่อไปนี้" pleaseLogin: "กรุณาเข้าสู่ระบบเพื่ออนุมัติแอปพลิเคชัน" byClickingYouWillBeRedirectedToThisUrl: "หากอนุญาตการเข้าถึง ระบบจะเปลี่ยนเส้นทางไปยัง URL ด้านล่างโดยอัตโนมัติ" + alreadyAuthorized: "แอปพลิเคชันนี้ได้รับอนุญาตให้เข้าถึงแล้ว" _antennaSources: all: "โน้ตทั้งหมด" homeTimeline: "โน้ตจากผู้ใช้ที่ติดตาม" @@ -2489,6 +2546,44 @@ _widgets: clicker: "คลิกเกอร์" birthdayFollowings: "วันเกิดผู้ใช้ในวันนี้" chat: "แชตเลย" +_widgetOptions: + showHeader: "แสดงส่วนหัว" + transparent: "ทำพื้นหลังโปรงใส" + height: "ความสูง" + _button: + colored: "สี" + _clock: + size: "ขนาด" + thickness: "ความหนาเข็ม" + thicknessThin: "บาง" + thicknessMedium: "ปานกลาง" + thicknessThick: "หนา" + graduations: "ขีดบอกค่าบนหน้าปัด" + graduationDots: "จุด" + graduationArabic: "เลขอารบิก" + fadeGraduations: "เฟดหน้าปัด" + sAnimation: "การเคลื่อนไหวของเข็มวินาที" + sAnimationElastic: "สมจริง" + sAnimationEaseOut: "ลื่นๆ" + twentyFour: "ระบบ 24 ชั่วโมง" + labelTime: "เวลา" + labelTz: "เขตเวลา" + labelTimeAndTz: "เวลาและเขตเวลา" + timezone: "เขตเวลา" + showMs: "แสดงมิลลิวินาที" + showLabel: "แสดงป้าย" + _jobQueue: + sound: "เล่นเสียง" + _rss: + url: "URL ของฟีด RSS" + refreshIntervalSec: "ห้วงอัปเดต (วินาที)" + maxEntries: "จำนวนที่แสดงได้สูงสุด" + _rssTicker: + shuffle: "สุ่มลำดับ" + duration: "ความเร็วทิกเกอร์ (วินาที)" + reverse: "วิ่งไปอีกทาง" + _birthdayFollowings: + period: "ระยะเวลา" _cw: hide: "ซ่อน" show: "โหลดเพิ่มเติม" @@ -2533,9 +2628,20 @@ _postForm: replyPlaceholder: "ตอบกลับโน้ตนี้..." quotePlaceholder: "อ้างโน้ตนี้..." channelPlaceholder: "โพสต์ลงช่อง..." + showHowToUse: "แสดงวิธีใช้ฟอร์ม" _howToUse: + content_title: "เนื้อความ" + content_description: "ป้อนเนื้อหาที่จะโพสต์" + toolbar_title: "แถบเครื่องมือ" + toolbar_description: "สามารถแนบไฟล์หรือแบบสอบถาม ตั้งข้อความเกริ่นหรือแฮชแท็ก แทรกเอโมจิหรือการกล่าวถึง เป็นต้น" + account_title: "เมนูบัญชี" + account_description: "สามารถสลับบัญชีที่ใช้โพสต์ หรือดูรายการฉบับร่างและโพสต์กำหนดเวลาไว้ซึ่งบันทึกไว้ในบัญชีได้" visibility_title: "การมองเห็น" + visibility_description: "สามารถตั้งค่าขอบเขตการเผยแพร่โน้ตได้" menu_title: "เมนู" + menu_description: "สามารถบันทึกเป็นฉบับร่าง ตั้งเวลาการโพสต์ ตั้งค่ารีแอคชั่น และดำเนินการอื่นๆ ได้" + submit_title: "ปุ่มโพสต์" + submit_description: "กดปุ่มนั้นเพื่อโพสต์โน้ต หรือกด Ctrl + Enter / Cmd + Return เพื่อโพสต์ก็ได้เช่นกัน" _placeholders: a: "ตอนนี้เป็นยังไงบ้าง?" b: "มีอะไรเกิดขึ้นหรือเปล่า?" @@ -2551,7 +2657,7 @@ _profile: metadata: "ข้อมูลเพิ่มเติม" metadataEdit: "แก้ไขข้อมูลเพิ่มเติม" metadataDescription: "ใช้สิ่งเหล่านี้ คุณสามารถแสดงฟิลด์ข้อมูลเพิ่มเติมในโปรไฟล์ของคุณ" - metadataLabel: "ป้ายชื่อ" + metadataLabel: "ป้าย" metadataContent: "เนื้อหา" changeAvatar: "เปลี่ยนไอคอนประจำตัว" changeBanner: "เปลี่ยนแบนเนอร์" @@ -2712,6 +2818,8 @@ _notification: quote: "อ้างอิง" reaction: "รีแอคชั่น" pollEnded: "โพลสิ้นสุดแล้ว" + scheduledNotePosted: "โพสต์กำหนดเวลาสำเร็จ" + scheduledNotePostFailed: "โพสต์กำหนดเวลาล้มเหลว" receiveFollowRequest: "ได้รับคำร้องขอติดตาม" followRequestAccepted: "อนุมัติให้ติดตามแล้ว" roleAssigned: "ให้บทบาท" @@ -2751,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "ความกว้างขั้นต่ำนั้นจะถูกใช้งานสำหรับสิ่งนี้เมื่อเปิดใช้งานตัวเลือก \"ปรับความกว้างอัตโนมัติ\" หากเลือกเปิดใช้งานแล้ว" flexible: "ปรับความกว้างอัตโนมัติ" enableSyncBetweenDevicesForProfiles: "เปิดใช้งานการซิงค์ข้อมูลโปรไฟล์ระหว่างอุปกรณ์" + showHowToUse: "แสดงวิธีใช้ UI" + _howToUse: + addColumn_title: "เพิ่มคอลัมน์" + addColumn_description: "สามารถเลือกประเภทของคอลัมน์แล้วเพิ่มได้" + settings_title: "ตั้งค่า UI" + settings_description: "สามารถตั้งค่ารายละเอียดของ UI แบบเด็คได้" + switchProfile_title: "สลับโปรไฟล์" + switchProfile_description: "สามารถบันทึกเลย์เอาต์ของ UI เป็นโปรไฟล์ และสลับใช้งานได้ทุกเมื่อ" _columns: main: "หลัก" widgets: "วิดเจ็ต" @@ -2811,6 +2927,8 @@ _abuseReport: notifiedWebhook: "Webhook ที่ใช้" deleteConfirm: "ต้องการลบปลายทางการแจ้งเตือนใช่ไหม?" _moderationLogTypes: + clearQueue: "ล้างคิว" + promoteQueue: "ดันงานในคิวอีกครั้ง" createRole: "สร้างบทบาทแล้ว" deleteRole: "ลบบทบาทแล้ว" updateRole: "อัปเดตบทบาทแล้ว" @@ -2869,7 +2987,7 @@ _fileViewer: uploadedAt: "วันที่เข้าร่วม" attachedNotes: "โน้ตที่แนบมาด้วย" usage: "ใช้แล้ว" - thisPageCanBeSeenFromTheAuthor: "หน้าเพจนี้จะสามารถปรากฏได้โดยผู้ใช้ที่อัปโหลดไฟล์นี้เท่านั้น" + thisPageCanBeSeenFromTheAuthor: "เฉพาะผู้ใช้ที่อัปโหลดไฟล์นี้เท่านั้นที่สามารถดูหน้าเพจนี้ได้" _externalResourceInstaller: title: "ติดตั้งจากไซต์ภายนอก" checkVendorBeforeInstall: "โปรดตรวจสอบให้แน่ใจว่าแหล่งแจกหน่ายมีความน่าเชื่อถือก่อนทำการติดตั้ง" @@ -3054,7 +3172,7 @@ _customEmojisManager: uploadSettingDescription: "สามารถกำหนดพฤติกรรมขณะอัปโหลดเอโมจิจากหน้าจอนี้ได้" directoryToCategoryLabel: "ป้อนชื่อไดเรกทอรีเป็น \"category\"" directoryToCategoryCaption: "เมื่อทำการลากและวางไดเรกทอรี ชื่อจะถูกป้อนเป็น \"category\"" - confirmRegisterEmojisDescription: "จะลงทะเบียนเอโมจิที่แสดงในรายการเป็นเอโมจิแบบกำหนดเองใหม่\nดำเนินการต่อหรือไม่? (เพื่อหลีกเลี่ยงภาระโหลดหนัก ระบบจะสามารถลงทะเบียนอีโมจิได้สูงสุด {count} รายการต่อครั้ง)" + confirmRegisterEmojisDescription: "จะลงทะเบียนเอโมจิที่แสดงในรายการเป็นเอโมจิแบบกำหนดเองใหม่\nดำเนินการต่อหรือไม่? (เพื่อหลีกเลี่ยงภาระโหลดหนัก ระบบจะสามารถลงทะเบียนเอโมจิได้สูงสุด {count} รายการต่อครั้ง)" confirmClearEmojisDescription: "ต้องการยกเลิกการแก้ไขและล้างรายการเอโมจิที่แสดงอยู่หรือไม่?" confirmUploadEmojisDescription: "จะอัปโหลดไฟล์ {count} รายการที่ลากและวางไปยังไดรฟ์ ดำเนินการหรือไม่?" _embedCodeGen: @@ -3205,6 +3323,7 @@ _watermarkEditor: title: "แก้ไขลายน้ำ" cover: "ซ้อนทับทั่วทั้งพื้นที่" repeat: "ปูให้เต็มพื้นที่" + preserveBoundingRect: "ปรับไม่ให้ล้นขอบเมื่อหมุน" opacity: "ความทึบแสง" scale: "ขนาด" text: "ข้อความ" @@ -3226,11 +3345,12 @@ _watermarkEditor: polkadotSubDotRadius: "ขนาดของจุดรอง" polkadotSubDotDivisions: "จำนวนจุดรอง" leaveBlankToAccountUrl: "เว้นว่างไว้หากต้องการใช้ URL ของบัญชีแทน" + failedToLoadImage: "โหลดภาพล้มเหลว" _imageEffector: title: "เอฟเฟกต์" addEffect: "เพิ่มเอฟเฟกต์" discardChangesConfirm: "ต้องการทิ้งการเปลี่ยนแปลงแล้วออกหรือไม่?" - nothingToConfigure: "ไม่มีอะไรให้ตั้งค่า" + failedToLoadImage: "โหลดภาพล้มเหลว" _fxs: chromaticAberration: "ความคลาดสี" glitch: "กลิตช์" @@ -3281,11 +3401,7 @@ _imageEffector: threshold: "เทรชโฮลด์" centerX: "กลาง X" centerY: "กลาง Y" - zoomLinesSmoothing: "ทำให้สมูธ" - zoomLinesSmoothingDescription: "ตั้งให้สมูธไม่สามารถใช้ร่วมกับตั้งความกว้างเส้นรวมศูนย์ได้" - zoomLinesThreshold: "ความกว้างเส้นรวมศูนย์" zoomLinesMaskSize: "ขนาดพื้นที่ตรงกลาง" - zoomLinesBlack: "ทำให้ดำ" circle: "ทรงกลม" drafts: "ร่าง" _drafts: diff --git a/locales/tr-TR.yml b/locales/tr-TR.yml index 208022a6d9..b05c62bb25 100644 --- a/locales/tr-TR.yml +++ b/locales/tr-TR.yml @@ -83,6 +83,8 @@ files: "Dosyalar" download: "İndir" driveFileDeleteConfirm: "“{name}” dosyasını silmek istediğinden emin misin? Bu dosyaya ekli tüm notlar da silinecek." unfollowConfirm: "{name} kullanıcısını cidden takipden çıkmak istiyor musun?" +cancelFollowRequestConfirm: "{name} adlı kişiye gönderdiğiniz takip isteğini iptal etmek ister misiniz?" +rejectFollowRequestConfirm: "{name} adlı kullanıcının takip isteğini reddetmek istiyor musunuz?" exportRequested: "Dışa aktarma işlemi talep ettin. Bu işlem biraz zaman alabilir. İşlem tamamlandığında Drive'ına eklenecek." importRequested: "İçe aktarma talebinde bulundun. Bu işlem biraz zaman alabilir." lists: "Listeler" @@ -253,6 +255,7 @@ noteDeleteConfirm: "Bu notu silmek istediğinden emin misin?" pinLimitExceeded: "Artık daha fazla not sabitleyemezsin" done: "Tamam" processing: "İşleniyor..." +preprocessing: "Hazırlık aşamasında" preview: "Önizleme" default: "Varsayılan" defaultValueIs: "Varsayılan: {value}" @@ -301,6 +304,7 @@ uploadFromUrlMayTakeTime: "Yükleme işleminin tamamlanması biraz zaman alabili uploadNFiles: "{n} dosya yükle" explore: "Keşfet" messageRead: "Oku" +readAllChatMessages: "Tüm mesajları okundu olarak işaretle" noMoreHistory: "Daha fazla geçmiş bilgisi yok." startChat: "Sohbete başla" nUsersRead: "{n} tarafından okundu" @@ -333,6 +337,7 @@ fileName: "Dosya adı" selectFile: "Dosya seçin" selectFiles: "Dosyaları seçin" selectFolder: "Klasör seçin" +unselectFolder: "Klasör seçimini kaldır" selectFolders: "Klasörleri seçin" fileNotSelected: "Hiç dosya seçilmedi" renameFile: "Dosyayı yeniden adlandır" @@ -345,6 +350,7 @@ addFile: "Bir dosya ekle" showFile: "Dosyaları göster" emptyDrive: "Drive boş" emptyFolder: "Bu klasör boş" +dropHereToUpload: "Yüklemek için dosyalarınızı buraya sürükleyin." unableToDelete: "Silinemiyor" inputNewFileName: "Yeni bir dosya adı girin" inputNewDescription: "Yeni alternatif metin girin" @@ -537,6 +543,7 @@ regenerate: "Yeniden oluştur" fontSize: "Yazı tipi boyutu" mediaListWithOneImageAppearance: "Tek bir resim içeren medya listelerinin yüksekliği" limitTo: "{x} ile sınırlandır" +showMediaListByGridInWideArea: "Ekran genişliği geniş olduğunda, medya listesi yatay olarak görüntülenecektir." noFollowRequests: "Bekleyen takip istekleri yok." openImageInNewTab: "Görüntüleri yeni sekmede aç" dashboard: "Gösterge paneli" @@ -772,6 +779,7 @@ lockedAccountInfo: "Notunuzun görünürlüğünü “Yalnızca takipçiler” o alwaysMarkSensitive: "Varsayılan olarak hassas olarak işaretle" loadRawImages: "Küçük resimleri göstermek yerine orijinal resimleri yükle" disableShowingAnimatedImages: "Animasyonlu görüntüleri oynatmayın" +disableShowingAnimatedImages_caption: "Bu ayara rağmen animasyonlu görüntüler oynatılmıyorsa, bunun nedeni tarayıcınızın veya işletim sisteminizin erişilebilirlik ayarları veya güç tasarrufu ayarlarından kaynaklanan parazit olabilir." highlightSensitiveMedia: "Hassas medyayı vurgulayın" verificationEmailSent: "Doğrulama e-postası gönderildi. Doğrulamayı tamamlamak için e-postadaki bağlantıyı takip edin." notSet: "Ayarlı değil" @@ -1018,6 +1026,9 @@ pushNotificationAlreadySubscribed: "Push bildirimleri zaten açık" pushNotificationNotSupported: "Push bildirimleri sunucu veya tarayıcı tarafından desteklenmiyor" sendPushNotificationReadMessage: "Okunduktan sonra push bildirimlerini silin" sendPushNotificationReadMessageCaption: "Bu, cihazınızın güç tüketimini artırabilir." +pleaseAllowPushNotification: "Lütfen tarayıcı ayarlarınızdan bildirimlere izin verin." +browserPushNotificationDisabled: "Bildirim gönderme izni alınamadı." +browserPushNotificationDisabledDescription: "{serverName} sunucusundan bildirim gönderme izniniz yok. Lütfen tarayıcı ayarlarınızdan bildirimlere izin verin ve tekrar deneyin." windowMaximize: "Maksimize et" windowMinimize: "Minimize et" windowRestore: "Geri yükle" @@ -1168,6 +1179,7 @@ installed: "Yüklendi" branding: "Markalaşma" enableServerMachineStats: "Sunucu donanım istatistiklerini yayınla" enableIdenticonGeneration: "Kullanıcı identicon oluşturmayı etkinleştir" +showRoleBadgesOfRemoteUsers: "Uzaktan kullanıcılara verilen rol rozetlerini görüntüle" turnOffToImprovePerformance: "Devre dışı bırakma, daha yüksek performansa yol açabilir." createInviteCode: "Davet Kodu oluştur" createWithOptions: "Seçeneklerle oluştur" @@ -1316,6 +1328,7 @@ acknowledgeNotesAndEnable: "Önlemleri anladıktan sonra açın." federationSpecified: "Bu sunucu, beyaz liste federasyonunda çalıştırılmaktadır. Yönetici tarafından belirlenen sunucular dışında diğer sunucularla etkileşim kurmak yasaktır." federationDisabled: "Bu sunucuda federasyon devre dışıdır. Diğer sunuculardaki kullanıcılarla etkileşim kuramazsınız." draft: "Taslaklar" +draftsAndScheduledNotes: "Taslaklar ve planlanmış gönderiler" confirmOnReact: "Tepki verirken onaylayın" reactAreYouSure: "“{emoji}” tepkisini eklemek ister misin?" markAsSensitiveConfirm: "Bu medyayı hassas olarak ayarlamak ister misin?" @@ -1344,6 +1357,7 @@ textCount: "Karakter sayısı" information: "Hakkında" chat: "Sohbet" directMessage: "Kullanıcıyla sohbet et" +directMessage_short: "Mesaj" migrateOldSettings: "Eski istemci ayarlarını taşıma" migrateOldSettings_description: "Bu işlem otomatik olarak yapılmalıdır, ancak herhangi bir nedenle geçiş başarısız olursa, geçiş işlemini manuel olarak kendin başlatabilirsin. Mevcut yapılandırma bilgileri üzerine yazılacaktır." compress: "Sıkıştır" @@ -1371,6 +1385,8 @@ redisplayAllTips: "Tüm “İpucu & Püf Nokta” tekrar göster" hideAllTips: "Tüm “İpucu & Püf Nokta” gizle" defaultImageCompressionLevel: "Varsayılan görüntü sıkıştırma düzeyi" defaultImageCompressionLevel_description: "Düşük seviye görüntü kalitesini korur ancak dosya boyutunu artırır.
Yüksek seviye dosya boyutunu azaltır ancak görüntü kalitesini düşürür." +defaultCompressionLevel: "Varsayılan sıkıştırma seviyesi" +defaultCompressionLevel_description: "Ayarı düşürmek kaliteyi koruyacak ancak dosya boyutunu artıracaktır.
Ayarı yükseltmek dosya boyutunu küçültecek ancak kaliteyi düşürecektir." inMinutes: "Dakika(lar)" inDays: "Gün(ler)" safeModeEnabled: "Güvenli mod etkinleştirildi" @@ -1378,21 +1394,74 @@ pluginsAreDisabledBecauseSafeMode: "Güvenli mod etkinleştirildiği için tüm customCssIsDisabledBecauseSafeMode: "Güvenli mod etkin olduğu için özel CSS uygulanmıyor." themeIsDefaultBecauseSafeMode: "Güvenli mod etkinken, varsayılan tema kullanılır. Güvenli modu devre dışı bırakmak bu değişiklikleri geri alır." thankYouForTestingBeta: "Beta sürümünü test ettiğin için teşekkür ederiz!" +createUserSpecifiedNote: "Kullanıcı tarafından belirtilen notlar oluşturun" +schedulePost: "Bir gönderi planla" +scheduleToPostOnX: "{x} için bir gönderi planla" +scheduledToPostOnX: "{x} için bir gönderi planlandı." +schedule: "rezervasyon" +scheduled: "rezervasyon" widgets: "Widget'lar" +deviceInfo: "Cihaz Bilgileri" +deviceInfoDescription: "Teknik bir sorunuz olduğunda, aşağıdaki bilgileri eklemeniz sorunun çözülmesine yardımcı olabilir." +youAreAdmin: "Siz yöneticisiniz." +frame: "Çerçeve" presets: "Ön ayar" +zeroPadding: "Sıfır doldurma" +nothingToConfigure: "Ayarlar seçeneği bulunmamaktadır." _imageEditing: _vars: + caption: "Dosya başlığı" filename: "Dosya adı" + filename_without_ext: "Uzantısız dosya adları" + year: "Çekim yılı" + month: "Çekim ayı" + day: "Çekim tarihi" + hour: "Fotoğrafın çekildiği zaman (saat)" + minute: "Çekim süresi (dakika)" + second: "Çekim süresi (saniye)" + camera_model: "Kamera Adı" + camera_lens_model: "Lens adı" + camera_mm: "Odak uzaklığı" + camera_mm_35: "Genişlik (35mm)" + camera_f: "açıklık" + camera_s: "Enstantane hızı" + camera_iso: "ISO hassasiyeti" + gps_lat: "Enlem" + gps_long: "Boylam" _imageFrameEditor: + title: "Düzenleme kareleri" + tip: "Görselleri, meta verileri içeren çerçeveler ve etiketler ekleyerek süsleyebilirsiniz." header: "Başlık" + footer: "Alt bilgi" + borderThickness: "jantın genişliği" + labelThickness: "Etiket genişliği" + labelScale: "Etiket ölçeği" + centered: "Merkezlenmiş" + captionMain: "Altyazı (büyük)" + captionSub: "Altyazı (küçük)" + availableVariables: "Mevcut değişkenler" + withQrCode: "2 boyutlu kod" + backgroundColor: "Arka Plan Rengi " + textColor: "Metin Rengi " font: "Yazı tipi" fontSerif: "Serif" fontSansSerif: "Sans Serif" quitWithoutSaveConfirm: "Kaydedilmemiş değişiklikleri silmek ister misin?" + failedToLoadImage: "Görüntü yükleme başarısız oldu " +_compression: + _quality: + high: "Yüksek Kalite " + medium: "Orta Kalite" + low: "Düşük Kalite " + _size: + large: "Büyük Boyut" + medium: "Orta Boyut" + small: "Küçük Boyut" _order: newest: "Önce yeni" oldest: "Önce eski" _chat: + messages: "Mesaj" noMessagesYet: "Henüz mesaj yok" newMessage: "Yeni mesaj" individualChat: "Özel Sohbet" @@ -1481,6 +1550,11 @@ _settings: showUrlPreview: "URL önizlemesi" showAvailableReactionsFirstInNote: "Mevcut tepkileri en üstte göster." showPageTabBarBottom: "Sayfa sekme çubuğunu aşağıda göster" + emojiPaletteBanner: "Emoji seçiciye kalıcı olarak bir palet olarak görüntülenecek ön ayarları kaydedebilir veya seçicinin nasıl görüntüleneceğini özelleştirebilirsiniz." + enableAnimatedImages: "Hareketli görüntüleri etkinleştirin" + settingsPersistence_title: "Ayarların kalıcılığı" + settingsPersistence_description1: "Ayarların kalıcı olarak saklanmasını etkinleştirmek, yapılandırma bilgilerinin kaybolmasını önler." + settingsPersistence_description2: "Ortamınıza bağlı olarak bu özelliği etkinleştirmek mümkün olmayabilir." _chat: showSenderName: "Gönderenin adını göster" sendOnEnter: "Enter tuşuna basarak gönderin" @@ -1489,6 +1563,8 @@ _preferencesProfile: profileNameDescription: "Bu cihazı tanımlayan bir ad belirle." profileNameDescription2: "Örnek: “Ana bilgisayar”, “Akıllı telefon”" manageProfiles: "Profilleri Yönet" + shareSameProfileBetweenDevicesIsNotRecommended: "Aynı profili birden fazla cihazda kullanmak önerilmez." + useSyncBetweenDevicesOptionIfYouWantToSyncSetting: "Birden fazla cihazda senkronize etmek istediğiniz ayarlarınız varsa, lütfen her bir ayar için \"Birden fazla cihazda senkronize et\" seçeneğini etkinleştirin." _preferencesBackup: autoBackup: "Otomatik yedekleme" restoreFromBackup: "Yedeklemeden geri yükle" @@ -1498,6 +1574,7 @@ _preferencesBackup: youNeedToNameYourProfileToEnableAutoBackup: "Otomatik yedeklemeyi etkinleştirmek için bir profil adı ayarlanmalıdır." autoPreferencesBackupIsNotEnabledForThisDevice: "Bu cihazda ayarların otomatik yedeklemesi etkinleştirilmemiş." backupFound: "Ayarların yedeği bulundu" + forceBackup: "Ayarların zorunlu yedeklenmesi" _accountSettings: requireSigninToViewContents: "İçeriği görüntülemek için oturum açmanız gerekir." requireSigninToViewContentsDescription1: "Oluşturduğun tüm notları ve diğer içeriği görüntülemek için oturum açman gerekir. Bu, tarayıcıların bilgilerini toplamasına engel olacaktır." @@ -2003,6 +2080,7 @@ _role: canManageAvatarDecorations: "Avatar süslerini yönet" driveCapacity: "Drive kapasitesi" maxFileSize: "Yükleyebileceğin maksimum dosya boyutu" + maxFileSize_caption: "Önceki aşamada ters proxy veya CDN gibi başka yapılandırma ayarları da olabilir." alwaysMarkNsfw: "Dosyaları her zaman NSFW olarak işaretle" canUpdateBioMedia: "Bir simge veya banner görüntüsünü düzenleyebilir" pinMax: "Sabitlenmiş notların maksimum sayısı" @@ -2030,6 +2108,7 @@ _role: uploadableFileTypes_caption: "İzin verilen MIME/dosya türlerini belirtir. Birden fazla MIME türü, yeni bir satırla ayırarak belirtilebilir ve joker karakterler yıldız işareti (*) ile belirtilebilir. (örneğin, image/*)" uploadableFileTypes_caption2: "Bazı dosya türleri algılanamayabilir. Bu tür dosyalara izin vermek için, spesifikasyona {x} ekle." noteDraftLimit: "Sunucu notlarının olası taslak sayısı" + scheduledNoteLimit: "Aynı anda oluşturulabilecek planlanmış gönderi sayısı" watermarkAvailable: "Filigran işlevinin kullanılabilirliği" _condition: roleAssignedTo: "Manuel rollere atanmış" @@ -2420,6 +2499,7 @@ _auth: scopeUser: "Aşağıdaki kullanıcı olarak çalıştırın" pleaseLogin: "Uygulamaları yetkilendirmek için lütfen giriş yapın." byClickingYouWillBeRedirectedToThisUrl: "Erişim izni verildiğinde, otomatik olarak aşağıdaki URL'ye yönlendirileceksin." + alreadyAuthorized: "Bu uygulamaya zaten erişim izinleri verilmiş durumda." _antennaSources: all: "Tüm notlar" homeTimeline: "Takip edilen kullanıcıların notları" @@ -2466,6 +2546,44 @@ _widgets: clicker: "Tıklayıcı" birthdayFollowings: "Bugünün Doğum Günleri" chat: "Sohbet" +_widgetOptions: + showHeader: "Başlığı göster" + transparent: "Arka planı şeffaf yapın" + height: "Yükseklik" + _button: + colored: "Renkli" + _clock: + size: "Boyut" + thickness: "İğne kalınlığı" + thicknessThin: "İnce" + thicknessMedium: "Normal" + thicknessThick: "Kalın" + graduations: "Kadran ölçeği" + graduationDots: "Nokta" + graduationArabic: "Arap rakamları" + fadeGraduations: "ölçeği soluklaştır" + sAnimation: "İkinci el animasyon" + sAnimationElastic: "Gerçek" + sAnimationEaseOut: "Düz" + twentyFour: "24 saat ekran" + labelTime: "Zaman" + labelTz: "Zaman Dilimi" + labelTimeAndTz: "Zaman ve Saat Dilimi" + timezone: "Zaman Dilimi " + showMs: "Milisaniye cinsinden göster" + showLabel: "Etiketi Göster" + _jobQueue: + sound: "Sesleri Çal" + _rss: + url: "RSS beslemesi URL'si" + refreshIntervalSec: "Güncelleme aralığı (saniye)" + maxEntries: "Görüntülenecek maksimum öğe sayısı" + _rssTicker: + shuffle: "Görüntüleme sırasını karıştır" + duration: "Kaydırma yazısı hızı (saniye)" + reverse: "Geriye doğru kaydır" + _birthdayFollowings: + period: "Süre" _cw: hide: "Gizle" show: "İçeriği göster" @@ -2510,9 +2628,20 @@ _postForm: replyPlaceholder: "Bu notu yanıtla..." quotePlaceholder: "Bu notu alıntı yap..." channelPlaceholder: "Bir kanala gönder..." + showHowToUse: "Form açıklamasını göster" _howToUse: + content_title: "Metin" + content_description: "Yayınlamak istediğiniz içeriği girin." + toolbar_title: "Araç Çubuğu" + toolbar_description: "Dosya ve anket ekleyebilir, açıklamalar ve etiketler ekleyebilir, emoji ve bahsetme mesajları ekleyebilirsiniz." + account_title: "Hesap Menüsü" + account_description: "Paylaşım yaptığınız hesabı değiştirebilir ve hesabınıza kaydedilmiş taslak ve planlanmış paylaşımların listesini görüntüleyebilirsiniz." visibility_title: "Görünürlük" + visibility_description: "Notlarınıza kimlerin erişebileceğinin kapsamını belirleyebilirsiniz." menu_title: "Menü" + menu_description: "Taslak olarak kaydetme, gönderi planlama ve tepki ayarlama gibi diğer işlemleri de gerçekleştirebilirsiniz." + submit_title: "Gönder düğmesi" + submit_description: "Bir not paylaşacağım. Ctrl + Enter / Cmd + Enter tuşlarını kullanarak da paylaşım yapabilirsiniz." _placeholders: a: "Ne yapıyorsun?" b: "Çevrende neler oluyor?" @@ -2658,6 +2787,8 @@ _notification: youReceivedFollowRequest: "Bir takip isteği aldınız." yourFollowRequestAccepted: "Takip isteğin kabul edildi." pollEnded: "Anket sonuçları açıklandı." + scheduledNotePosted: "Rezervasyon defteri yayınlandı." + scheduledNotePostFailed: "Rezervasyon defterine gönderilemedi" newNote: "Yeni not" unreadAntennaNote: "{name} anteni" roleAssigned: "Verilen rol" @@ -2687,6 +2818,8 @@ _notification: quote: "Alıntılar" reaction: "Tepki" pollEnded: "Anketler sona eriyor" + scheduledNotePosted: "Planlanan gönderi başarılı" + scheduledNotePostFailed: "Planlanan gönderi başarısız oldu" receiveFollowRequest: "Takip istekleri alındı" followRequestAccepted: "Kabul edilen takip istekleri" roleAssigned: "Verilen rol" @@ -2726,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "“Otomatik genişlik ayarı” seçeneği etkinleştirildiğinde, bunun için minimum genişlik kullanılacak." flexible: "Otomatik genişlik ayarı" enableSyncBetweenDevicesForProfiles: "Cihazlar arasında profil bilgilerinin senkronizasyonunu etkinleştir" + showHowToUse: "Kullanıcı arayüzü açıklamasını görüntüle" + _howToUse: + addColumn_title: "Sütun ekle" + addColumn_description: "Sütun türlerini seçip ekleyebilirsiniz." + settings_title: "Arayüz Yapılandırması" + settings_description: "Sekme kullanıcı arayüzünü ayrıntılı olarak yapılandırabilirsiniz." + switchProfile_title: "Profili Değiştir" + switchProfile_description: "Kullanıcı arayüzü düzenlerini profil olarak kaydedebilir ve istediğiniz zaman bunlar arasında geçiş yapabilirsiniz." _columns: main: "Ana" widgets: "Widget'lar" @@ -2786,6 +2927,8 @@ _abuseReport: notifiedWebhook: "Kullanılacak webhook" deleteConfirm: "Bildirim alıcısını silmek istediğinden emin misin?" _moderationLogTypes: + clearQueue: "Kuyruğu temizle" + promoteQueue: "Sıraya alınmış işi yeniden deneyin." createRole: "Rol oluşturuldu" deleteRole: "Rol silindi" updateRole: "Rol güncellendi" @@ -3180,10 +3323,13 @@ _watermarkEditor: title: "Filigranı Düzenle" cover: "Her şeyi örtün" repeat: "her yere yayılmış" + preserveBoundingRect: "Döndürme sırasında dışarı çıkmayacak şekilde ayarlayın." opacity: "Opaklık" scale: "Boyut" text: "Metin" + qr: "2 boyutlu kod" position: "Pozisyon" + margin: "Kenar" type: "Tür" image: "Görseller" advanced: "Gelişmiş" @@ -3198,17 +3344,21 @@ _watermarkEditor: polkadotSubDotOpacity: "İkincil noktanın opaklığı" polkadotSubDotRadius: "İkincil noktanın boyutu" polkadotSubDotDivisions: "Alt nokta sayısı." + leaveBlankToAccountUrl: "Boş bırakılması durumunda hesap URL'si görüntülenecektir." + failedToLoadImage: "Görüntü yükleme başarısız oldu " _imageEffector: title: "Effektler" addEffect: "Efektler Ekle" discardChangesConfirm: "Cidden çıkmak istiyor musun? Kaydedilmemiş değişikliklerin var." - nothingToConfigure: "Yapılandırılabilir seçenekler mevcut değildir." + failedToLoadImage: "Görüntü yükleme başarısız oldu " _fxs: chromaticAberration: "Renk Sapması" glitch: "Bozulma" mirror: "Ayna" invert: "Renkleri Ters Çevir" grayscale: "Gri tonlama" + blur: "Bulanıklık" + pixelate: "Mozaik" colorAdjust: "Renk Düzeltme" colorClamp: "Renk Sıkıştırma" colorClampAdvanced: "Renk Sıkıştırma (Gelişmiş)" @@ -3220,10 +3370,13 @@ _imageEffector: checker: "Denetleyici" blockNoise: "Gürültüyü Engelle" tearing: "Yırtılma" + fill: "Doldur" _fxProps: angle: "Açı" scale: "Boyut" size: "Boyut" + radius: "Yarıçap" + samples: "Örnek sayısı" offset: "Pozisyon" color: "Renk" opacity: "Opaklık" @@ -3248,11 +3401,10 @@ _imageEffector: threshold: "Eşik" centerX: "Merkez X" centerY: "Merkez Y" - zoomLinesSmoothing: "Düzeltme" - zoomLinesSmoothingDescription: "Düzeltme ve yakınlaştırma çizgi genişliği birlikte kullanılamaz." - zoomLinesThreshold: "Zoom çizgi genişliği" + density: "Yoğunluk" + zoomLinesOutlineThickness: "çizgi gölge kalınlığı" zoomLinesMaskSize: "Merkez çapı" - zoomLinesBlack: "Siyah yap" + circle: "Dairesel" drafts: "Taslaklar" _drafts: select: "Taslak Seç" @@ -3268,6 +3420,22 @@ _drafts: restoreFromDraft: "Taslaktan geri yükle" restore: "Geri yükle" listDrafts: "Taslaklar Listesi" + schedule: "Planlanmış Gönderi" + listScheduledNotes: "Planlanmış gönderilerin listesi" + cancelSchedule: "Rezervasyonu iptal et" +qr: "2 boyutlu kod" _qr: showTabTitle: "Ekran" + readTabTitle: "Okumak" + shareTitle: "{name}{acct}" + shareText: "Beni Fediverse'te takip edin!" + chooseCamera: "Kamera Seç" + cannotToggleFlash: "Işık seçeneği mevcut değil." + turnOnFlash: "Işığı açın" + turnOffFlash: "Işığı kapatın" + startQr: "Özgeçmiş Kodu Okuyucu" + stopQr: "Kod okuyucuyu durdurun" + noQrCodeFound: "QR kodu bulunamadı" + scanFile: "Cihazdaki görüntüyü tarayın" raw: "Metin" + mfm: "MFM" diff --git a/locales/uk-UA.yml b/locales/uk-UA.yml index c399e4c29c..273ccfb078 100644 --- a/locales/uk-UA.yml +++ b/locales/uk-UA.yml @@ -1430,6 +1430,14 @@ _widgets: userList: "Список користувачів" _userList: chooseList: "Виберіть список" +_widgetOptions: + height: "Висота" + _button: + colored: "Кольоровий" + _clock: + size: "Розмір" + _birthdayFollowings: + period: "Тривалість" _cw: hide: "Сховати" show: "Показати більше" diff --git a/locales/uz-UZ.yml b/locales/uz-UZ.yml index 5d7c63dd15..11db034823 100644 --- a/locales/uz-UZ.yml +++ b/locales/uz-UZ.yml @@ -945,6 +945,12 @@ _widgets: jobQueue: "Vazifalar navbati" _userList: chooseList: "Ro'yxat tanlash" +_widgetOptions: + height: "balandligi" + _button: + colored: "rangli" + _birthdayFollowings: + period: "Davomiylik" _cw: show: "Ko‘proq ko‘rish" chars: "{count} ta belgi(lar)" diff --git a/locales/vi-VN.yml b/locales/vi-VN.yml index e0204ae4f8..f4e6e568bb 100644 --- a/locales/vi-VN.yml +++ b/locales/vi-VN.yml @@ -1,5 +1,5 @@ --- -_lang_: "Tiếng Việt " +_lang_: "Tiếng Việt" headlineMisskey: "Mạng xã hội liên hợp" introMisskey: "Xin chào! Misskey là một nền tảng tiểu blog phi tập trung mã nguồn mở.\nViết \"tút\" để chia sẻ những suy nghĩ của bạn 📡\nBằng \"biểu cảm\", bạn có thể bày tỏ nhanh chóng cảm xúc của bạn với các tút 👍\nHãy khám phá một thế giới mới! 🚀" poweredByMisskeyDescription: "{name} là một trong những chủ máy của Misskey là nền tảng mã nguồn mở" @@ -576,6 +576,7 @@ showFixedPostForm: "Hiện khung soạn tút ở phía trên bảng tin" showFixedPostFormInChannel: "Hiển thị mẫu bài đăng ở phía trên bản tin" withRepliesByDefaultForNewlyFollowed: "Mặc định hiển thị trả lời từ những người dùng mới theo dõi trong dòng thời gian" newNoteRecived: "Đã nhận tút mới" +newNote: "Ghi chú mới" sounds: "Âm thanh" sound: "Âm thanh" notificationSoundSettings: "Cài đặt âm thanh thông báo" @@ -848,7 +849,7 @@ hideOnlineStatus: "Ẩn trạng thái online" hideOnlineStatusDescription: "Ẩn trạng thái online của bạn làm giảm sự tiện lợi của một số tính năng như tìm kiếm." online: "Online" active: "Hoạt động" -offline: "Offline" +offline: "Ngoại tuyến" notRecommended: "Không đề xuất" botProtection: "Bảo vệ Bot" instanceBlocking: "Máy chủ đã chặn" @@ -1220,6 +1221,7 @@ information: "Giới thiệu" chat: "Trò chuyện" migrateOldSettings: "Di chuyển cài đặt cũ" migrateOldSettings_description: "Thông thường, quá trình này diễn ra tự động, nhưng nếu vì lý do nào đó mà quá trình di chuyển không thành công, bạn có thể kích hoạt thủ công quy trình di chuyển, quá trình này sẽ ghi đè lên thông tin cấu hình hiện tại của bạn." +driveAboutTip: "Trong Drive, danh sách các tệp bạn đã tải lên trước đây sẽ được hiển thị.
\nBạn có thể sử dụng lại chúng khi đính kèm vào ghi chú, hoặc tải lên trước các tệp để đăng sau.
\nLưu ý rằng nếu bạn xóa một tệp, tệp đó cũng sẽ biến mất khỏi tất cả những nơi đã sử dụng tệp đó (ghi chú, trang, ảnh đại diện, biểu ngữ, v.v.).
\nBạn cũng có thể tạo các thư mục để sắp xếp chúng." inMinutes: "phút" inDays: "ngày" widgets: "Tiện ích" @@ -1826,6 +1828,14 @@ _widgets: _userList: chooseList: "Chọn danh sách" clicker: "clicker" +_widgetOptions: + height: "Chiều cao" + _button: + colored: "Với màu" + _clock: + size: "Kích thước" + _birthdayFollowings: + period: "Thời hạn" _cw: hide: "Ẩn" show: "Tải thêm" diff --git a/locales/zh-CN.yml b/locales/zh-CN.yml index caae928605..5cfa90e910 100644 --- a/locales/zh-CN.yml +++ b/locales/zh-CN.yml @@ -10,7 +10,7 @@ notifications: "通知" username: "用户名" password: "密码" initialPasswordForSetup: "初始化密码" -initialPasswordIsIncorrect: "初始化密码不正确" +initialPasswordIsIncorrect: "初始化密码不正确。" initialPasswordForSetupDescription: "如果是自己安装的 Misskey,请输入配置文件里设好的密码。\n如果使用的是 Misskey 的托管服务等,请输入服务商提供的密码。\n如果没有设置密码,请留空并继续。" forgotPassword: "忘记密码" fetchingAsApObject: "在联邦宇宙查询中..." @@ -146,11 +146,11 @@ markAsSensitive: "标记为敏感内容" unmarkAsSensitive: "取消标记为敏感内容" enterFileName: "输入文件名" mute: "屏蔽" -unmute: "取消屏蔽" -renoteMute: "屏蔽转帖" -renoteUnmute: "取消屏蔽转帖" -block: "拉黑" -unblock: "取消拉黑" +unmute: "取消隐藏" +renoteMute: "隐藏转帖" +renoteUnmute: "取消隐藏转帖" +block: "屏蔽" +unblock: "取消屏蔽" suspend: "冻结" unsuspend: "解除冻结" blockConfirm: "确定要屏蔽吗?" @@ -164,7 +164,7 @@ selectAntenna: "选择天线" editAntenna: "编辑天线" createAntenna: "创建天线" selectWidget: "选择小工具" -editWidgets: "编辑部件" +editWidgets: "编辑小工具" editWidgetsExit: "完成编辑" customEmojis: "自定义表情符号" emoji: "表情符号" @@ -241,13 +241,13 @@ clearCachedFilesConfirm: "确定要清除所有缓存的远程文件吗?" blockedInstances: "被屏蔽的服务器" blockedInstancesDescription: "设定要屏蔽的服务器,以换行分隔。被屏蔽的服务器将无法与本服务器进行交换通讯。子域名也同样会被屏蔽。" silencedInstances: "被静音的服务器" -silencedInstancesDescription: "设置要静音的服务器,以换行分隔。被静音的服务器内所有的账户都被视为「静音」状态,且关注操作均需要被批准。被阻止的实例不受影响。" +silencedInstancesDescription: "设置要静音的服务器,以换行分隔。被静音的服务器内所有的账户都被视为「静音」状态,且关注操作均需要被批准。已被屏蔽的实例不受影响。" mediaSilencedInstances: "已隐藏媒体文件的服务器" -mediaSilencedInstancesDescription: "设置要隐藏媒体文件的服务器,以换行分隔。被设置的服务器内所有账号的文件均按照「敏感内容」处理,且将无法使用自定义表情符号。被阻止的实例不受影响。" +mediaSilencedInstancesDescription: "设置要隐藏媒体文件的服务器,以换行分隔。被设置的服务器内所有账号的文件均按照「敏感内容」处理,且将无法使用自定义表情符号。已被屏蔽的实例不受影响。" federationAllowedHosts: "允许联合的服务器" federationAllowedHostsDescription: "设定允许联合的服务器,以换行分隔。" -muteAndBlock: "屏蔽/拉黑" -mutedUsers: "已静音的用户" +muteAndBlock: "隐藏/屏蔽" +mutedUsers: "已隐藏的用户" blockedUsers: "已屏蔽的用户" noUsers: "无用户" editProfile: "编辑资料" @@ -262,7 +262,7 @@ defaultValueIs: "默认值: {value}" noCustomEmojis: "没有自定义表情符号" noJobs: "没有任务" federating: "联合中" -blocked: "已拉黑" +blocked: "已屏蔽" suspended: "停止投递" all: "全部" subscribing: "已订阅" @@ -543,6 +543,7 @@ regenerate: "重新生成" fontSize: "字体大小" mediaListWithOneImageAppearance: "仅一张图片的媒体列表高度" limitTo: "上限为 {x}" +showMediaListByGridInWideArea: "在大屏幕上并排显示媒体列表" noFollowRequests: "没有关注请求" openImageInNewTab: "在新标签页中打开图片" dashboard: "管理面板" @@ -645,7 +646,7 @@ addedRelays: "已添加的中继" serviceworkerInfo: "您需要启用推送通知" deletedNote: "已删除的帖子" invisibleNote: "隐藏的帖子" -enableInfiniteScroll: "启用自动滚动页面模式" +enableInfiniteScroll: "自动加载更多内容" visibility: "可见性" poll: "投票" useCw: "隐藏内容" @@ -693,13 +694,13 @@ emptyToDisableSmtpAuth: "用户名和密码留空可以禁用 SMTP 验证" smtpSecure: "在 SMTP 连接中使用隐式 SSL / TLS" smtpSecureInfo: "使用 STARTTLS 时关闭。" testEmail: "邮件发送测试" -wordMute: "屏蔽关键词" +wordMute: "折叠关键词" wordMuteDescription: "折叠包含指定关键词的帖子。被折叠的帖子可单击展开。" -hardWordMute: "强屏蔽关键词" -showMutedWord: "显示屏蔽关键词" -hardWordMuteDescription: "隐藏包含指定关键词的帖子。与隐藏关键词不同,帖子将完全不会显示。" +hardWordMute: "屏蔽关键词" +showMutedWord: "显示已折叠的关键词" +hardWordMuteDescription: "屏蔽包含指定关键词的帖子。与折叠关键词不同,帖子将完全不会显示。" regexpError: "正则表达式错误" -regexpErrorDescription: "{tab} 隐藏文字的第 {line} 行的正则表达式有错误:" +regexpErrorDescription: "{tab} 折叠关键词的第 {line} 行的正则表达式有错误:" instanceMute: "已隐藏的服务器" userSaysSomething: "{name} 说了什么,但是被屏蔽词过滤了" userSaysSomethingAbout: "{name} 说了关于「{word}」的什么" @@ -831,7 +832,7 @@ youAreRunningUpToDateClient: "您所使用的客户端已经是最新的。" newVersionOfClientAvailable: "新版本的客户端可用。" usageAmount: "使用量" capacity: "容量" -inUse: "使用中" +inUse: "已使用" editCode: "编辑代码" apply: "应用" receiveAnnouncementFromInstance: "从服务器接收通知" @@ -912,7 +913,7 @@ accountDeletionInProgress: "正在删除账户" usernameInfo: "在服务器上唯一标识您的帐户的名称。您可以使用字母 (a ~ z, A ~ Z)、数字 (0 ~ 9) 和下划线 (_)。用户名以后不能更改。" aiChanMode: "小蓝模式" devMode: "开发者模式" -keepCw: "回复时维持隐藏内容" +keepCw: "始终开启内容警告" pubSub: "Pub/Sub 账户" lastCommunication: "最近通信" resolved: "已解决" @@ -931,8 +932,8 @@ manageAccounts: "管理账户" makeReactionsPublic: "将回应设置为公开" makeReactionsPublicDescription: "将您发表过的回应设置成公开可见。" classic: "经典" -muteThread: "屏蔽帖文串" -unmuteThread: "取消屏蔽帖文串" +muteThread: "静音帖文串" +unmuteThread: "取消帖文串静音" followingVisibility: "关注的人的公开范围" followersVisibility: "关注者的公开范围" continueThread: "查看更多帖子" @@ -955,7 +956,7 @@ searchByGoogle: "Google" instanceDefaultLightTheme: "服务器默认浅色主题" instanceDefaultDarkTheme: "服务器默认深色主题" instanceDefaultThemeDescription: "以对象格式输入主题代码" -mutePeriod: "屏蔽期限" +mutePeriod: "隐藏时长" period: "截止时间" indefinitely: "永久" tenMinutes: "10分钟" @@ -1293,7 +1294,7 @@ useNativeUIForVideoAudioPlayer: "使用浏览器的 UI 播放动画及音频" keepOriginalFilename: "保持原文件名" keepOriginalFilenameDescription: "若关闭此设置,上传文件时文件名将被替换为随机字符。" noDescription: "没有描述" -alwaysConfirmFollow: "总是确认关注" +alwaysConfirmFollow: "在关注时始终确认" inquiry: "联系我们" tryAgain: "请再试一次" confirmWhenRevealingSensitiveMedia: "显示敏感内容前需要确认" @@ -1334,7 +1335,7 @@ markAsSensitiveConfirm: "要将此媒体标记为敏感吗?" unmarkAsSensitiveConfirm: "要将此媒体解除敏感标记吗?" preferences: "偏好设置" accessibility: "辅助功能" -preferencesProfile: "设置的配置" +preferencesProfile: "设置的配置文件" copyPreferenceId: "复制设置 ID" resetToDefaultValue: "重置为默认值" overrideByAccount: "覆盖账号" @@ -1351,7 +1352,7 @@ preferenceSyncConflictChoiceDevice: "设备上的设定值" preferenceSyncConflictChoiceCancel: "取消同步" paste: "粘贴" emojiPalette: "表情符号调色板" -postForm: "投稿窗口" +postForm: "发帖窗口" textCount: "字数" information: "关于" chat: "聊天" @@ -1374,10 +1375,10 @@ advice: "建议" realtimeMode: "实时模式" turnItOn: "开启" turnItOff: "关闭" -emojiMute: "屏蔽表情符号" -emojiUnmute: "取消屏蔽表情符号" -muteX: "屏蔽{x}" -unmuteX: "取消屏蔽{x}" +emojiMute: "打码表情符号" +emojiUnmute: "取消表情符号打码" +muteX: "隐藏{x}" +unmuteX: "取消对{x}的隐藏" abort: "中止" tip: "提示和技巧" redisplayAllTips: "重新显示所有的提示和技巧" @@ -1406,6 +1407,7 @@ youAreAdmin: "你是管理员" frame: "边框" presets: "预设值" zeroPadding: "填充 0" +nothingToConfigure: "没有项目" _imageEditing: _vars: caption: "文件标题" @@ -1485,7 +1487,7 @@ _chat: home: "首页" send: "发送" newline: "换行" - muteThisRoom: "屏蔽该群聊" + muteThisRoom: "消息免打扰" deleteRoom: "删除群聊" chatNotAvailableForThisAccountOrServer: "此服务器或者账户还未开启聊天功能。" chatIsReadOnlyForThisAccountOrServer: "此服务器或者账户内的聊天为只读。无法发布新信息或创建及加入群聊。" @@ -1548,13 +1550,16 @@ _settings: showUrlPreview: "显示 URL 预览" showAvailableReactionsFirstInNote: "在顶部显示可用的回应" showPageTabBarBottom: "在下方显示页面标签栏" - emojiPaletteBanner: "可以将固定显示表情符号选择器的预设注册至调色板,也可以自定义表情符号选择器的显示方式。" + emojiPaletteBanner: "可以将固定显示在表情符号选择器中的预设注册为调色板,也可以自定义表情符号选择器的显示方式。" enableAnimatedImages: "启用动画图像" + settingsPersistence_title: "设置持久化" + settingsPersistence_description1: "启用设置持久化可防止设置信息丢失。" + settingsPersistence_description2: "根据环境不同,有可能无法开启。" _chat: showSenderName: "显示发送者的名字" sendOnEnter: "回车键发送" _preferencesProfile: - profileName: "配置名" + profileName: "配置文件名" profileNameDescription: "请指定用于识别此设备的名称" profileNameDescription2: "如「PC」、「手机」等" manageProfiles: "管理配置文件" @@ -2080,7 +2085,7 @@ _role: canUpdateBioMedia: "可以更新头像和横幅" pinMax: "帖子置顶数量限制" antennaMax: "可创建的最大天线数量" - wordMuteMax: "屏蔽词的字数限制" + wordMuteMax: "折叠词的字数限制" webhookMax: "Webhook 创建数量限制" clipMax: "便签创建数量限制" noteEachClipsMax: "便签内贴文的最大数量" @@ -2251,14 +2256,14 @@ _menuDisplay: top: "顶部" hide: "隐藏" _wordMute: - muteWords: "要隐藏的词" + muteWords: "要折叠的词" muteWordsDescription: "AND 条件用空格分隔,OR 条件用换行符分隔。" muteWordsDescription2: "正则表达式用斜线包裹" _instanceMute: - instanceMuteDescription: "屏蔽服务器中所有的帖子和转帖,包括该服务器内用户的回复。" + instanceMuteDescription: "隐藏来自这些服务器的所有帖子和转贴,包括这些服务器上用户的回复。" instanceMuteDescription2: "通过换行符分隔进行设置" title: "下面实例中的帖子将被隐藏。" - heading: "已屏蔽的服务器" + heading: "已隐藏的服务器" _theme: explore: "寻找主题" install: "安装主题" @@ -2397,8 +2402,8 @@ _2fa: _permissions: "read:account": "查看账户信息" "write:account": "更改帐户信息" - "read:blocks": "查看黑名单" - "write:blocks": "编辑黑名单" + "read:blocks": "查看屏蔽列表" + "write:blocks": "编辑屏蔽列表" "read:drive": "查看网盘" "write:drive": "管理网盘文件" "read:favorites": "查看收藏夹" @@ -2407,8 +2412,8 @@ _permissions: "write:following": "关注/取消关注" "read:messaging": "查看私信" "write:messaging": "撰写或删除消息" - "read:mutes": "查看屏蔽列表" - "write:mutes": "编辑屏蔽列表" + "read:mutes": "查看已隐藏用户列表" + "write:mutes": "编辑已隐藏用户列表" "write:notes": "撰写或删除帖子" "read:notifications": "查看通知" "write:notifications": "管理通知" @@ -2512,7 +2517,7 @@ _weekday: _widgets: profile: "个人资料" instanceInfo: "服务器信息" - memo: "便签" + memo: "便利贴" notifications: "通知" timeline: "时间线" calendar: "日历" @@ -2525,11 +2530,11 @@ _widgets: digitalClock: "数字时钟" unixClock: "UNIX 时钟" federation: "联合" - instanceCloud: "服务器云" - postForm: "投稿窗口" + instanceCloud: "服务器球状列表" + postForm: "发帖窗口" slideshow: "幻灯片展示" button: "按钮" - onlineUsers: "在线用户" + onlineUsers: "在线用户数" jobQueue: "作业队列" serverMetric: "服务器指标" aiscript: "AiScript 控制台" @@ -2541,6 +2546,44 @@ _widgets: clicker: "点击器" birthdayFollowings: "今天是他们的生日" chat: "私信" +_widgetOptions: + showHeader: "显示标题" + transparent: "使背景透明" + height: "高度" + _button: + colored: "彩色" + _clock: + size: "大小" + thickness: "指针宽度" + thicknessThin: "细" + thicknessMedium: "普通" + thicknessThick: "粗" + graduations: "表盘刻度" + graduationDots: "点" + graduationArabic: "阿拉伯数字" + fadeGraduations: "淡化表盘" + sAnimation: "秒针动画" + sAnimationElastic: "跳动" + sAnimationEaseOut: "平滑" + twentyFour: "24 小时制" + labelTime: "时间" + labelTz: "时区" + labelTimeAndTz: "时间和时区" + timezone: "时区" + showMs: "显示毫秒" + showLabel: "显示标签" + _jobQueue: + sound: "播放音效" + _rss: + url: "RSS feed 的 URL" + refreshIntervalSec: "更新间隔(秒)" + maxEntries: "最大显示个数" + _rssTicker: + shuffle: "随机顺序" + duration: "滚动速度(秒)" + reverse: "反方向滚动" + _birthdayFollowings: + period: "期限" _cw: hide: "隐藏" show: "查看更多" @@ -2628,10 +2671,10 @@ _exportOrImport: favoritedNotes: "收藏的帖子" clips: "便签" followingList: "关注中" - muteList: "屏蔽" - blockingList: "拉黑" + muteList: "隐藏" + blockingList: "屏蔽" userLists: "列表" - excludeMutingUsers: "排除屏蔽用户" + excludeMutingUsers: "排除已隐藏用户" excludeInactiveUsers: "排除不活跃用户" withReplies: "在时间线中包含导入用户的回复" _charts: @@ -2812,10 +2855,18 @@ _deck: introduction: "将各列进行组合以创建您自己的界面!" introduction2: "可以随时通过屏幕右侧的 + 来添加列" widgetsIntroduction: "从列菜单中,选择“小工具编辑”来添加小工具" - useSimpleUiForNonRootPages: "用简易UI表示非根页面" + useSimpleUiForNonRootPages: "使用简易UI显示导航页面" usedAsMinWidthWhenFlexible: "「自适应宽度」被启用的时候,这就是最小的宽度" flexible: "自适应宽度" - enableSyncBetweenDevicesForProfiles: "启用个人资料信息跨设备同步" + enableSyncBetweenDevicesForProfiles: "启用配置文件跨设备同步" + showHowToUse: "查看用户界面说明" + _howToUse: + addColumn_title: "添加列" + addColumn_description: "可以选择要添加的列的类型。" + settings_title: "用户界面设置" + settings_description: "可以配置 Deck UI 的详细设置," + switchProfile_title: "切换配置文件" + switchProfile_description: "将用户界面布局保存为配置文件,以便随时切换。" _columns: main: "主列" widgets: "小工具" @@ -3064,10 +3115,10 @@ _mediaControls: playbackRate: "播放速度" loop: "循环播放" _contextMenu: - title: "上下文菜单" - app: "应用" - appWithShift: "Shift 键应用" - native: "浏览器的用户界面" + title: "右键菜单" + app: "使用" + appWithShift: "按住 Shift 键使用" + native: "浏览器的原生界面" _gridComponent: _error: requiredValue: "此值为必填项" @@ -3299,7 +3350,6 @@ _imageEffector: title: "效果" addEffect: "添加效果" discardChangesConfirm: "丢弃当前设置并退出?" - nothingToConfigure: "还没有设置" failedToLoadImage: "图片加载失败" _fxs: chromaticAberration: "色差" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "阈值" centerX: "中心 X " centerY: "中心 Y" - zoomLinesSmoothing: "平滑" - zoomLinesSmoothingDescription: "平滑和集中线宽度设置不能同时使用。" - zoomLinesThreshold: "集中线宽度" + density: "密度" + zoomLinesOutlineThickness: "线条阴影粗细" zoomLinesMaskSize: "中心直径" - zoomLinesBlack: "变成黑色" circle: "圆形" drafts: "草稿" _drafts: diff --git a/locales/zh-TW.yml b/locales/zh-TW.yml index 5227423d84..fa8a3eead8 100644 --- a/locales/zh-TW.yml +++ b/locales/zh-TW.yml @@ -297,7 +297,7 @@ keepOriginalUploading: "保留原圖" keepOriginalUploadingDescription: "上傳圖片時保留原始圖片。關閉時,瀏覽器會在上傳時生成適用於網路傳送的版本。" fromDrive: "從雲端空間中選擇" fromUrl: "從 URL 上傳" -uploadFromUrl: "從網址上傳" +uploadFromUrl: "從 URL 上傳" uploadFromUrlDescription: "您要上傳的檔案網址" uploadFromUrlRequested: "已請求上傳" uploadFromUrlMayTakeTime: "還需要一些時間才能完成上傳。" @@ -543,6 +543,7 @@ regenerate: "再次生成" fontSize: "字體大小" mediaListWithOneImageAppearance: "只有一張圖片時的檔案列表高度" limitTo: "上限為 {x}" +showMediaListByGridInWideArea: "當畫面寬度較寬時,將媒體清單以橫向排列顯示" noFollowRequests: "沒有追隨您的請求" openImageInNewTab: "於新分頁中開啟圖片" dashboard: "儀表板" @@ -824,7 +825,7 @@ saveConfirm: "您要儲存變更嗎?" deleteConfirm: "你確定要刪除嗎?" invalidValue: "輸入值無效。" registry: "登錄表" -closeAccount: "停用帳戶" +closeAccount: "刪除帳戶" currentVersion: "目前版本" latestVersion: "最新版本" youAreRunningUpToDateClient: "您所使用的客戶端已經是最新的。" @@ -1089,9 +1090,9 @@ postToTheChannel: "發佈到頻道" cannotBeChangedLater: "之後不能變更。" reactionAcceptance: "接受表情反應" likeOnly: "僅限讚" -likeOnlyForRemote: "遠端僅限讚" +likeOnlyForRemote: "全部(遠端僅限讚)" nonSensitiveOnly: "僅限非敏感" -nonSensitiveOnlyForLocalLikeOnlyForRemote: "僅限非敏感(遠端僅限按讚)" +nonSensitiveOnlyForLocalLikeOnlyForRemote: "僅限非敏感(遠端僅限讚)" rolesAssignedToMe: "指派給自己的角色" resetPasswordConfirm: "重設密碼?" sensitiveWords: "敏感詞" @@ -1366,7 +1367,7 @@ top: "上" embed: "嵌入" settingsMigrating: "正在移轉設定。請稍候……(之後也可以到「設定 → 其他 → 舊設定資訊移轉」中手動進行移轉)" readonly: "唯讀" -goToDeck: "回去甲板" +goToDeck: "回到多欄模式" federationJobs: "聯邦通訊作業" driveAboutTip: "在「雲端硬碟」中,會顯示過去上傳的檔案列表。
\n可以在附加到貼文時重新利用,或者事先上傳之後再用於發布。
\n請注意,刪除檔案後,之前使用過該檔案的所有地方(貼文、頁面、大頭貼、橫幅等)也會一併無法顯示。
\n也可以建立資料夾來整理檔案。" scrollToClose: "用滾輪關閉" @@ -1393,7 +1394,7 @@ pluginsAreDisabledBecauseSafeMode: "由於啟用安全模式,所有的外掛 customCssIsDisabledBecauseSafeMode: "由於啟用安全模式,所有的客製 CSS 都被停用。" themeIsDefaultBecauseSafeMode: "在安全模式啟用期間將使用預設主題。關閉安全模式後會恢復原本的設定。" thankYouForTestingBeta: "感謝您協助驗證 beta 版!" -createUserSpecifiedNote: "建立使用者指定的筆記" +createUserSpecifiedNote: "建立指定使用者的貼文" schedulePost: "排定發布" scheduleToPostOnX: "排定在 {x} 發布" scheduledToPostOnX: "已排定在 {x} 發布貼文" @@ -1406,6 +1407,7 @@ youAreAdmin: "您是管理員" frame: "邊框" presets: "預設值" zeroPadding: "補零" +nothingToConfigure: "無可設定的項目" _imageEditing: _vars: caption: "檔案標題" @@ -1550,6 +1552,9 @@ _settings: showPageTabBarBottom: "在底部顯示頁面的標籤列" emojiPaletteBanner: "可以將固定顯示在表情符號選擇器的預設項目註冊為調色盤,或者自訂選擇器的顯示方式。" enableAnimatedImages: "啟用動畫圖片" + settingsPersistence_title: "設定的持久化" + settingsPersistence_description1: "啟用「設定的持久化」後,可以防止設定資訊遺失。" + settingsPersistence_description2: "依環境不同,可能無法啟用。" _chat: showSenderName: "顯示發送者的名稱" sendOnEnter: "按下 Enter 發送訊息" @@ -2152,7 +2157,7 @@ _accountDelete: accountDelete: "刪除帳戶" mayTakeTime: "刪除帳戶的處理負荷較大,如果帳戶發佈的內容以及上傳的檔案數量較多,則需要一段時間才能完成。" sendEmail: "帳戶刪除完成後,將向其電子郵件地址發送通知。" - requestAccountDelete: "刪除帳戶請求" + requestAccountDelete: "請求刪除帳戶" started: "已開始刪除作業。" inProgress: "正在刪除" _ad: @@ -2356,7 +2361,7 @@ _timeIn: minutes: "{n}分鐘後" hours: "{n}小時後" days: "{n}天後" - weeks: "{n}周後" + weeks: "{n}週後" months: "{n}個月後" years: "{n}年後" _time: @@ -2541,6 +2546,44 @@ _widgets: clicker: "點擊器" birthdayFollowings: "今天生日的使用者" chat: "聊天" +_widgetOptions: + showHeader: "檢視標頭 " + transparent: "使背景透明" + height: "高度" + _button: + colored: "彩色" + _clock: + size: "尺寸" + thickness: "指針粗細" + thicknessThin: "細" + thicknessMedium: "普通" + thicknessThick: "粗" + graduations: "刻度盤" + graduationDots: "圓點" + graduationArabic: "阿拉伯數字" + fadeGraduations: "刻度淡出" + sAnimation: "秒針的動畫效果" + sAnimationElastic: "真實的" + sAnimationEaseOut: "滑順" + twentyFour: "24 小時制" + labelTime: "時間" + labelTz: "時區" + labelTimeAndTz: "時間與時區" + timezone: "時區" + showMs: "顯示毫秒" + showLabel: "顯示標記" + _jobQueue: + sound: "播放音效" + _rss: + url: "RSS 訂閱網址" + refreshIntervalSec: "更新間隔(秒)" + maxEntries: "最大顯示數量" + _rssTicker: + shuffle: "顯示順序隨機排列" + duration: "RSS 跑馬燈的捲動速度(秒)" + reverse: "反方向滾動" + _birthdayFollowings: + period: "時長" _cw: hide: "隱藏" show: "顯示內容" @@ -2816,6 +2859,14 @@ _deck: usedAsMinWidthWhenFlexible: "如果啟用「自動調整寬度」,此為最小寬度" flexible: "自動調整寬度" enableSyncBetweenDevicesForProfiles: "啟用裝置與裝置之間的設定檔資料同步化" + showHowToUse: "檢視使用者介面說明" + _howToUse: + addColumn_title: "新增欄位" + addColumn_description: "您可以選擇要新增的欄位類型。" + settings_title: "使用者介面設定" + settings_description: "您可以對多欄模式使用者介面做詳細設定。" + switchProfile_title: "切換設定檔" + switchProfile_description: "將使用者介面佈局儲存為設定檔,就可以隨時切換使用。" _columns: main: "主列" widgets: "小工具" @@ -3299,7 +3350,6 @@ _imageEffector: title: "特效" addEffect: "新增特效" discardChangesConfirm: "捨棄更改並退出嗎?" - nothingToConfigure: "無可設定的項目" failedToLoadImage: "圖片載入失敗" _fxs: chromaticAberration: "色差" @@ -3351,11 +3401,9 @@ _imageEffector: threshold: "閾值" centerX: "X中心座標" centerY: "Y中心座標" - zoomLinesSmoothing: "平滑化" - zoomLinesSmoothingDescription: "平滑化與集中線寬度設定不能同時使用。" - zoomLinesThreshold: "集中線的寬度" + density: "密度" + zoomLinesOutlineThickness: "線條陰影的粗細" zoomLinesMaskSize: "中心直徑" - zoomLinesBlack: "變成黑色" circle: "圓形" drafts: "草稿\n" _drafts: diff --git a/package.json b/package.json index ac94d1834e..b70960417a 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "misskey", - "version": "2025.12.2-beta.0", + "version": "2026.3.2", "codename": "nasubi", "repository": { "type": "git", "url": "https://github.com/misskey-dev/misskey.git" }, - "packageManager": "pnpm@10.25.0", + "packageManager": "pnpm@10.33.0", "workspaces": [ "packages/misskey-js", "packages/i18n", @@ -23,12 +23,12 @@ "private": true, "scripts": { "compile-config": "cd packages/backend && pnpm compile-config", - "build-pre": "node ./scripts/build-pre.js", + "build-pre": "node scripts/build-pre.mjs", "build-assets": "node ./scripts/build-assets.mjs", "build": "pnpm build-pre && pnpm -r build && pnpm build-assets", "build-storybook": "pnpm --filter frontend build-storybook", "build-misskey-js-with-types": "pnpm build-pre && pnpm --filter backend... --filter=!misskey-js build && pnpm --filter backend generate-api-json --no-build && ncp packages/backend/built/api.json packages/misskey-js/generator/api.json && pnpm --filter misskey-js update-autogen-code && pnpm --filter misskey-js build && pnpm --filter misskey-js api", - "start": "pnpm check:connect && cd packages/backend && pnpm compile-config && node ./built/boot/entry.js", + "start": "cd packages/backend && pnpm compile-config && node ./built/boot/entry.js", "start:inspect": "cd packages/backend && pnpm compile-config && node --inspect ./built/boot/entry.js", "start:test": "ncp ./.github/misskey/test.yml ./.config/test.yml && cd packages/backend && cross-env NODE_ENV=test pnpm compile-config && cross-env NODE_ENV=test node ./built/boot/entry.js", "cli": "cd packages/backend && pnpm cli", @@ -39,7 +39,7 @@ "migrateandstart": "pnpm migrate && pnpm start", "watch": "pnpm dev", "dev": "node scripts/dev.mjs", - "lint": "pnpm -r lint", + "lint": "pnpm --no-bail -r lint", "cy:open": "pnpm cypress open --config-file=cypress.config.ts", "cy:run": "pnpm cypress run", "e2e": "pnpm start-server-and-test start:test http://localhost:61812 cy:run", @@ -48,46 +48,45 @@ "jest-and-coverage": "cd packages/backend && pnpm jest-and-coverage", "test": "pnpm -r test", "test-and-coverage": "pnpm -r test-and-coverage", - "clean": "node ./scripts/clean.js", - "clean-all": "node ./scripts/clean-all.js", + "clean": "node scripts/clean.mjs", + "clean-all": "node scripts/clean-all.mjs", "cleanall": "pnpm clean-all" }, - "resolutions": { - "chokidar": "5.0.0", - "lodash": "4.17.21" - }, "dependencies": { - "cssnano": "7.1.2", - "esbuild": "0.27.1", + "cssnano": "7.1.3", + "esbuild": "0.27.4", "execa": "9.6.1", "ignore-walk": "8.0.0", "js-yaml": "4.1.1", - "postcss": "8.5.6", - "tar": "7.5.2", - "terser": "5.44.1", - "typescript": "5.9.3" + "postcss": "8.5.8", + "tar": "7.5.13", + "terser": "5.46.1" }, "devDependencies": { - "@eslint/js": "9.39.1", - "@misskey-dev/eslint-plugin": "2.2.0", + "@eslint/js": "9.39.4", + "@misskey-dev/eslint-plugin": "2.1.0", "@types/js-yaml": "4.0.9", - "@types/node": "24.10.2", - "@typescript-eslint/eslint-plugin": "8.49.0", - "@typescript-eslint/parser": "8.49.0", + "@types/node": "24.12.0", + "@typescript-eslint/eslint-plugin": "8.57.2", + "@typescript-eslint/parser": "8.57.2", + "@typescript/native-preview": "7.0.0-dev.20260116.1", "cross-env": "10.1.0", - "cypress": "15.7.1", - "eslint": "9.39.1", - "globals": "16.5.0", + "cypress": "15.13.0", + "eslint": "9.39.4", + "globals": "17.4.0", "ncp": "2.0.0", - "pnpm": "10.25.0", - "start-server-and-test": "2.1.3" + "pnpm": "10.33.0", + "start-server-and-test": "2.1.5", + "typescript": "5.9.3" }, "optionalDependencies": { "@tensorflow/tfjs-core": "4.22.0" }, "pnpm": { "overrides": { - "@aiscript-dev/aiscript-languageserver": "-" + "@aiscript-dev/aiscript-languageserver": "-", + "chokidar": "5.0.0", + "lodash": "4.17.23" }, "ignoredBuiltDependencies": [ "@sentry-internal/node-cpu-profiler", diff --git a/packages/backend/assets/api-doc.html b/packages/backend/assets/api-doc.html deleted file mode 100644 index 19e0349d47..0000000000 --- a/packages/backend/assets/api-doc.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - Misskey API - - - - - - - - - diff --git a/packages/backend/assets/api-doc.png b/packages/backend/assets/api-doc.png deleted file mode 100644 index 9b07f1f398..0000000000 Binary files a/packages/backend/assets/api-doc.png and /dev/null differ diff --git a/packages/backend/assets/misc/bios.js b/packages/backend/assets/misc/bios.js index 9ff5dca72a..f9716d8f00 100644 --- a/packages/backend/assets/misc/bios.js +++ b/packages/backend/assets/misc/bios.js @@ -9,7 +9,7 @@ window.onload = async () => { const account = JSON.parse(localStorage.getItem('account')); const i = account.token; - const api = (endpoint, data = {}) => { + const _api = (endpoint, data = {}) => { const promise = new Promise((resolve, reject) => { // Append a credential if (i) data.i = i; diff --git a/packages/backend/build.js b/packages/backend/build.js new file mode 100644 index 0000000000..52ca09b7a8 --- /dev/null +++ b/packages/backend/build.js @@ -0,0 +1,121 @@ +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import { build } from 'esbuild'; +import { swcPlugin } from 'esbuild-plugin-swc'; + +const _filename = fileURLToPath(import.meta.url); +const _dirname = dirname(_filename); +const _package = JSON.parse(fs.readFileSync(_dirname + '/package.json', 'utf-8')); + +const resolveTsPathsPlugin = { + name: 'resolve-ts-paths', + setup(build) { + build.onResolve({ filter: /^\.{1,2}\/.*\.js$/ }, (args) => { + if (args.importer) { + const absPath = join(args.resolveDir, args.path); + const tsPath = absPath.slice(0, -3) + '.ts'; + if (fs.existsSync(tsPath)) return { path: tsPath }; + const tsxPath = absPath.slice(0, -3) + '.tsx'; + if (fs.existsSync(tsxPath)) return { path: tsxPath }; + } + }); + }, +}; + +const externalIpaddrPlugin = { + name: 'external-ipaddr', + setup(build) { + build.onResolve({ filter: /^ipaddr\.js$/ }, (args) => { + return { path: args.path, external: true }; + }); + }, +}; + +/** @type {import('esbuild').BuildOptions} */ +const options = { + entryPoints: ['./src/boot/entry.ts'], + minify: true, + keepNames: true, + bundle: true, + outdir: './built/boot', + target: 'node22', + platform: 'node', + format: 'esm', + sourcemap: 'linked', + packages: 'external', + banner: { + js: 'import { createRequire as topLevelCreateRequire } from "module";' + + 'import ___url___ from "url";' + + 'const require = topLevelCreateRequire(import.meta.url);' + + 'const __filename = ___url___.fileURLToPath(import.meta.url);' + + 'const __dirname = ___url___.fileURLToPath(new URL(".", import.meta.url));', + }, + plugins: [ + externalIpaddrPlugin, + resolveTsPathsPlugin, + swcPlugin({ + jsc: { + parser: { + syntax: 'typescript', + decorators: true, + dynamicImport: true, + }, + transform: { + legacyDecorator: true, + decoratorMetadata: true, + }, + experimental: { + keepImportAssertions: true, + }, + baseUrl: join(_dirname, 'src'), + paths: { + '@/*': ['*'], + }, + target: 'esnext', + keepClassNames: true, + }, + }), + externalIpaddrPlugin, + ], + // external: [ + // 'slacc-*', + // 'class-transformer', + // 'class-validator', + // '@sentry/*', + // '@nestjs/websockets/socket-module', + // '@nestjs/microservices/microservices-module', + // '@nestjs/microservices', + // '@napi-rs/canvas-win32-x64-msvc', + // 'mock-aws-s3', + // 'aws-sdk', + // 'nock', + // 'sharp', + // 'jsdom', + // 're2', + // '@napi-rs/canvas', + // ], +}; + +const args = process.argv.slice(2).map(arg => arg.toLowerCase()); + +if (!args.includes('--no-clean')) { + fs.rmSync('./built', { recursive: true, force: true }); +} + +await buildSrc(); + +async function buildSrc() { + console.log(`[${_package.name}] start building...`); + + await build(options) + .then(() => { + console.log(`[${_package.name}] build succeeded.`); + }) + .catch((err) => { + process.stderr.write(err.stderr || err.message || err); + process.exit(1); + }); + + console.log(`[${_package.name}] finish building.`); +} diff --git a/packages/backend/eslint.config.js b/packages/backend/eslint.config.js index ba7c705def..d15a703ba2 100644 --- a/packages/backend/eslint.config.js +++ b/packages/backend/eslint.config.js @@ -25,7 +25,6 @@ export default [ }, }, rules: { - '@typescript-eslint/no-unused-vars': 'off', 'import/order': ['warn', { groups: [ 'builtin', diff --git a/packages/backend/migration/1767169026317-birthday-index.js b/packages/backend/migration/1767169026317-birthday-index.js new file mode 100644 index 0000000000..972fc08c9b --- /dev/null +++ b/packages/backend/migration/1767169026317-birthday-index.js @@ -0,0 +1,20 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export class BirthdayIndex1767169026317 { + name = 'BirthdayIndex1767169026317' + + async up(queryRunner) { + await queryRunner.query(`DROP INDEX "public"."IDX_de22cd2b445eee31ae51cdbe99"`); + await queryRunner.query(`CREATE OR REPLACE FUNCTION get_birthday_date(birthday TEXT) RETURNS SMALLINT AS $$ BEGIN RETURN CAST((SUBSTR(birthday, 6, 2) || SUBSTR(birthday, 9, 2)) AS SMALLINT); END; $$ LANGUAGE plpgsql IMMUTABLE;`); + await queryRunner.query(`CREATE INDEX "IDX_USERPROFILE_BIRTHDAY_DATE" ON "user_profile" (get_birthday_date("birthday"))`); + } + + async down(queryRunner) { + await queryRunner.query(`CREATE INDEX "IDX_de22cd2b445eee31ae51cdbe99" ON "user_profile" (substr("birthday", 6, 5))`); + await queryRunner.query(`DROP INDEX "public"."IDX_USERPROFILE_BIRTHDAY_DATE"`); + await queryRunner.query(`DROP FUNCTION IF EXISTS get_birthday_date(birthday TEXT)`); + } +} diff --git a/packages/backend/ormconfig.js b/packages/backend/ormconfig.js index dabc0893f4..1a8c146451 100644 --- a/packages/backend/ormconfig.js +++ b/packages/backend/ormconfig.js @@ -1,6 +1,6 @@ import { DataSource } from 'typeorm'; -import { loadConfig } from './built/config.js'; -import { entities } from './built/postgres.js'; +import { loadConfig } from './src-js/config.js'; +import { entities } from './src-js/postgres.js'; const isConcurrentIndexMigrationEnabled = process.env.MISSKEY_MIGRATION_CREATE_INDEX_CONCURRENTLY === '1'; diff --git a/packages/backend/package.json b/packages/backend/package.json index 206e2022c6..40d963f3c7 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -12,17 +12,17 @@ "start:test": "cross-env NODE_ENV=test pnpm compile-config && cross-env NODE_ENV=test node ./built/boot/entry.js", "migrate": "pnpm compile-config && pnpm typeorm migration:run -d ormconfig.js", "revert": "pnpm compile-config && pnpm typeorm migration:revert -d ormconfig.js", - "cli": "pnpm compile-config && node ./built/boot/cli.js", + "cli": "pnpm compile-config && node ./src-js/boot/cli.js", "check:connect": "pnpm compile-config && node ./scripts/check_connect.js", "compile-config": "node ./scripts/compile_config.js", - "build": "swc src -d built -D --strip-leading-paths", + "build": "swc src -d src-js -D --strip-leading-paths && node ./build.js", "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", + "build:tsc": "tsgo -p tsconfig.json && tsc-alias -p tsconfig.json", "watch": "pnpm compile-config && node ./scripts/watch.mjs", "restart": "pnpm build && pnpm start", "dev": "pnpm compile-config && node ./scripts/dev.mjs", - "typecheck": "tsc --noEmit && tsc -p test --noEmit && tsc -p test-federation --noEmit", + "typecheck": "tsgo --noEmit && tsgo -p test --noEmit && tsgo -p test-federation --noEmit", "eslint": "eslint --quiet \"{src,test-federation}/**/*.ts\"", "lint": "pnpm typecheck && pnpm eslint", "jest": "cross-env NODE_ENV=test pnpm compile-config && cross-env NODE_ENV=test node ./jest.js --forceExit --config jest.config.unit.cjs", @@ -41,20 +41,20 @@ }, "optionalDependencies": { "@swc/core-android-arm64": "1.3.11", - "@swc/core-darwin-arm64": "1.15.3", - "@swc/core-darwin-x64": "1.15.3", + "@swc/core-darwin-arm64": "1.15.21", + "@swc/core-darwin-x64": "1.15.21", "@swc/core-freebsd-x64": "1.3.11", - "@swc/core-linux-arm-gnueabihf": "1.15.3", - "@swc/core-linux-arm64-gnu": "1.15.3", - "@swc/core-linux-arm64-musl": "1.15.3", - "@swc/core-linux-x64-gnu": "1.15.3", - "@swc/core-linux-x64-musl": "1.15.3", - "@swc/core-win32-arm64-msvc": "1.15.3", - "@swc/core-win32-ia32-msvc": "1.15.3", - "@swc/core-win32-x64-msvc": "1.15.3", + "@swc/core-linux-arm-gnueabihf": "1.15.21", + "@swc/core-linux-arm64-gnu": "1.15.21", + "@swc/core-linux-arm64-musl": "1.15.21", + "@swc/core-linux-x64-gnu": "1.15.21", + "@swc/core-linux-x64-musl": "1.15.21", + "@swc/core-win32-arm64-msvc": "1.15.21", + "@swc/core-win32-ia32-msvc": "1.15.21", + "@swc/core-win32-x64-msvc": "1.15.21", "@tensorflow/tfjs": "4.22.0", "@tensorflow/tfjs-node": "4.22.0", - "bufferutil": "4.0.9", + "bufferutil": "4.1.0", "slacc-android-arm-eabi": "0.0.10", "slacc-android-arm64": "0.0.10", "slacc-darwin-arm64": "0.0.10", @@ -68,43 +68,42 @@ "slacc-linux-x64-musl": "0.0.10", "slacc-win32-arm64-msvc": "0.0.10", "slacc-win32-x64-msvc": "0.0.10", - "utf-8-validate": "6.0.5" + "utf-8-validate": "6.0.6" }, "dependencies": { - "@aws-sdk/client-s3": "3.947.0", - "@aws-sdk/lib-storage": "3.947.0", + "@aws-sdk/client-s3": "3.1016.0", + "@aws-sdk/lib-storage": "3.1016.0", "@discordapp/twemoji": "16.0.1", "@fastify/accepts": "5.0.4", - "@fastify/cors": "11.1.0", - "@fastify/express": "4.0.2", - "@fastify/http-proxy": "11.4.1", - "@fastify/multipart": "9.3.0", - "@fastify/static": "8.3.0", - "@kitajs/html": "4.2.11", + "@fastify/cors": "11.2.0", + "@fastify/express": "4.0.4", + "@fastify/http-proxy": "11.4.2", + "@fastify/multipart": "9.4.0", + "@fastify/static": "9.0.0", + "@kitajs/html": "4.2.13", "@misskey-dev/sharp-read-bmp": "1.2.0", "@misskey-dev/summaly": "5.2.5", - "@napi-rs/canvas": "0.1.84", - "@nestjs/common": "11.1.9", - "@nestjs/core": "11.1.9", - "@nestjs/testing": "11.1.9", + "@napi-rs/canvas": "0.1.97", + "@nestjs/common": "11.1.17", + "@nestjs/core": "11.1.17", + "@nestjs/testing": "11.1.17", "@peertube/http-signature": "1.7.0", - "@sentry/node": "10.29.0", - "@sentry/profiling-node": "10.29.0", - "@simplewebauthn/server": "13.2.2", - "@sinonjs/fake-timers": "15.0.0", - "@smithy/node-http-handler": "4.4.5", - "@swc/cli": "0.7.9", - "@swc/core": "1.15.3", + "@sentry/node": "10.45.0", + "@sentry/profiling-node": "10.45.0", + "@simplewebauthn/server": "13.3.0", + "@sinonjs/fake-timers": "15.1.1", + "@smithy/node-http-handler": "4.5.0", + "@swc/cli": "0.8.0", + "@swc/core": "1.15.21", "@twemoji/parser": "16.0.0", - "@types/redis-info": "3.0.3", "accepts": "1.3.8", - "ajv": "8.17.1", + "ajv": "8.18.0", "archiver": "7.0.1", "async-mutex": "0.5.0", "bcryptjs": "3.0.3", "blurhash": "2.0.5", - "body-parser": "2.2.1", - "bullmq": "5.65.1", + "body-parser": "2.2.2", + "bullmq": "5.71.0", "cacheable-lookup": "7.0.0", "chalk": "5.6.2", "chalk-template": "1.1.2", @@ -113,76 +112,74 @@ "content-disposition": "1.0.1", "date-fns": "4.1.0", "deep-email-validator": "0.1.21", - "fastify": "5.6.2", + "fastify": "5.8.4", "fastify-raw-body": "5.0.0", - "feed": "5.1.0", - "file-type": "21.1.1", + "feed": "5.2.0", + "file-type": "21.3.4", "fluent-ffmpeg": "2.1.3", "form-data": "4.0.5", - "got": "14.6.5", + "got": "14.6.6", "hpagent": "1.2.0", "http-link-header": "1.1.3", "i18n": "workspace:*", - "ioredis": "5.8.2", + "ioredis": "5.10.1", "ip-cidr": "4.0.2", "ipaddr.js": "2.3.0", "is-svg": "6.1.0", "json5": "2.2.3", "jsonld": "9.0.0", - "juice": "11.0.3", - "meilisearch": "0.54.0", + "juice": "11.1.1", + "meilisearch": "0.56.0", "mfm-js": "0.25.0", "mime-types": "3.0.2", "misskey-js": "workspace:*", "misskey-reversi": "workspace:*", "ms": "3.0.0-canary.202508261828", - "nanoid": "5.1.6", + "nanoid": "5.1.7", "nested-property": "4.0.0", "node-fetch": "3.3.2", - "node-html-parser": "7.0.1", - "nodemailer": "7.0.11", - "nsfwjs": "4.2.0", + "node-html-parser": "7.1.0", + "nodemailer": "8.0.3", + "nsfwjs": "4.3.0", "oauth2orize": "1.12.0", "oauth2orize-pkce": "0.1.2", "os-utils": "0.0.14", - "otpauth": "9.4.1", - "pg": "8.16.3", - "pkce-challenge": "5.0.1", + "otpauth": "9.5.0", + "pg": "8.20.0", + "pkce-challenge": "6.0.0", "probe-image-size": "7.2.3", "promise-limit": "2.7.0", "qrcode": "1.5.4", "random-seed": "0.3.0", "ratelimiter": "3.4.1", - "re2": "1.22.3", - "redis-info": "3.1.0", + "re2": "1.23.3", "reflect-metadata": "0.2.2", "rename": "1.0.4", "rss-parser": "3.13.0", "rxjs": "7.8.2", - "sanitize-html": "2.17.0", + "sanitize-html": "2.17.2", "secure-json-parse": "4.1.0", - "semver": "7.7.3", + "semver": "7.7.4", "sharp": "0.33.5", "slacc": "0.0.10", "strict-event-emitter-types": "2.0.0", "stringz": "2.1.0", - "systeminformation": "5.27.12", + "systeminformation": "5.31.5", "tinycolor2": "1.6.0", "tmp": "0.2.5", "tsc-alias": "1.8.16", "typeorm": "0.3.28", - "typescript": "5.9.3", "ulid": "3.0.2", "vary": "1.1.2", "web-push": "3.6.7", - "ws": "8.18.3", + "ws": "8.20.0", "xev": "3.0.2" }, "devDependencies": { "@jest/globals": "29.7.0", - "@kitajs/ts-html-plugin": "4.1.3", - "@nestjs/platform-express": "11.1.9", - "@sentry/vue": "10.29.0", + "@kitajs/ts-html-plugin": "4.1.4", + "@nestjs/platform-express": "11.1.17", + "@sentry/vue": "10.45.0", "@simplewebauthn/types": "12.0.0", "@swc/jest": "0.2.39", "@types/accepts": "1.3.7", @@ -196,18 +193,18 @@ "@types/jsonld": "1.5.15", "@types/mime-types": "3.0.1", "@types/ms": "2.1.0", - "@types/node": "24.10.2", - "@types/nodemailer": "7.0.4", + "@types/node": "24.12.0", + "@types/nodemailer": "7.0.11", "@types/oauth2orize": "1.11.5", "@types/oauth2orize-pkce": "0.1.2", - "@types/pg": "8.15.6", + "@types/pg": "8.20.0", "@types/qrcode": "1.5.6", "@types/random-seed": "0.3.5", "@types/ratelimiter": "3.4.6", "@types/rename": "1.0.7", - "@types/sanitize-html": "2.16.0", + "@types/sanitize-html": "2.16.1", "@types/semver": "7.7.1", - "@types/simple-oauth2": "5.0.7", + "@types/simple-oauth2": "5.0.8", "@types/sinonjs__fake-timers": "15.0.1", "@types/supertest": "6.0.3", "@types/tinycolor2": "1.4.6", @@ -215,21 +212,22 @@ "@types/vary": "1.1.3", "@types/web-push": "3.6.4", "@types/ws": "8.18.1", - "@typescript-eslint/eslint-plugin": "8.49.0", - "@typescript-eslint/parser": "8.49.0", + "@typescript-eslint/eslint-plugin": "8.57.2", + "@typescript-eslint/parser": "8.57.2", "aws-sdk-client-mock": "4.1.0", - "cbor": "10.0.11", + "cbor": "10.0.12", "cross-env": "10.1.0", + "esbuild-plugin-swc": "1.0.1", "eslint-plugin-import": "2.32.0", "execa": "9.6.1", - "fkill": "10.0.1", + "fkill": "10.0.3", "jest": "29.7.0", "jest-mock": "29.7.0", "js-yaml": "4.1.1", - "nodemon": "3.1.11", - "pid-port": "2.0.0", + "nodemon": "3.1.14", + "pid-port": "2.1.0", "simple-oauth2": "5.1.0", - "supertest": "7.1.4", - "vite": "7.2.7" + "supertest": "7.2.2", + "vite": "8.0.2" } } diff --git a/packages/backend/scripts/check_connect.js b/packages/backend/scripts/check_connect.js index 96c4549ccb..a1cb839303 100644 --- a/packages/backend/scripts/check_connect.js +++ b/packages/backend/scripts/check_connect.js @@ -4,8 +4,8 @@ */ import Redis from 'ioredis'; -import { loadConfig } from '../built/config.js'; -import { createPostgresDataSource } from '../built/postgres.js'; +import { loadConfig } from '../src-js/config.js'; +import { createPostgresDataSource } from '../src-js/postgres.js'; const config = loadConfig(); @@ -16,26 +16,22 @@ async function connectToPostgres() { } async function connectToRedis(redisOptions) { - return await new Promise(async (resolve, reject) => { - const redis = new Redis({ + let redis; + try { + redis = new Redis({ ...redisOptions, lazyConnect: true, reconnectOnError: false, showFriendlyErrorStack: true, }); - redis.on('error', e => reject(e)); - try { - await redis.connect(); - resolve(); - - } catch (e) { - reject(e); - - } finally { - redis.disconnect(false); - } - }); + await Promise.race([ + new Promise((_, reject) => redis.on('error', e => reject(e))), + redis.connect(), + ]); + } finally { + redis.disconnect(false); + } } // If not all of these are defined, the default one gets reused. @@ -50,7 +46,7 @@ const promises = Array ])) .map(connectToRedis) .concat([ - connectToPostgres() + connectToPostgres(), ]); await Promise.all(promises); diff --git a/packages/backend/scripts/generate_api_json.js b/packages/backend/scripts/generate_api_json.js index 798e243004..237f63a4d3 100644 --- a/packages/backend/scripts/generate_api_json.js +++ b/packages/backend/scripts/generate_api_json.js @@ -3,8 +3,8 @@ * SPDX-License-Identifier: AGPL-3.0-only */ +import { writeFileSync, existsSync } from 'node:fs'; import { execa } from 'execa'; -import { writeFileSync, existsSync } from "node:fs"; async function main() { if (!process.argv.includes('--no-build')) { @@ -19,10 +19,10 @@ async function main() { } /** @type {import('../src/config.js')} */ - const { loadConfig } = await import('../built/config.js'); + const { loadConfig } = await import('../src-js/config.js'); /** @type {import('../src/server/api/openapi/gen-spec.js')} */ - const { genOpenapiSpec } = await import('../built/server/api/openapi/gen-spec.js'); + const { genOpenapiSpec } = await import('../src-js/server/api/openapi/gen-spec.js'); const config = loadConfig(); const spec = genOpenapiSpec(config, true); diff --git a/packages/backend/scripts/measure-memory.mjs b/packages/backend/scripts/measure-memory.mjs index 017252d7ec..3f30e24fb4 100644 --- a/packages/backend/scripts/measure-memory.mjs +++ b/packages/backend/scripts/measure-memory.mjs @@ -14,24 +14,56 @@ import { fork } from 'node:child_process'; import { setTimeout } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; +import * as http from 'node:http'; +import * as fs from 'node:fs/promises'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); +const SAMPLE_COUNT = 3; // Number of samples to measure const STARTUP_TIMEOUT = 120000; // 120 seconds timeout for server startup const MEMORY_SETTLE_TIME = 10000; // Wait 10 seconds after startup for memory to settle -async function measureMemory() { - const startTime = Date.now(); +const keys = { + VmPeak: 0, + VmSize: 0, + VmHWM: 0, + VmRSS: 0, + VmData: 0, + VmStk: 0, + VmExe: 0, + VmLib: 0, + VmPTE: 0, + VmSwap: 0, +}; +async function getMemoryUsage(pid) { + const status = await fs.readFile(`/proc/${pid}/status`, 'utf-8'); + + const result = {}; + for (const key of Object.keys(keys)) { + const match = status.match(new RegExp(`${key}:\\s+(\\d+)\\s+kB`)); + if (match) { + result[key] = parseInt(match[1], 10); + } else { + throw new Error(`Failed to parse ${key} from /proc/${pid}/status`); + } + } + + return result; +} + +async function measureMemory() { // Start the Misskey backend server using fork to enable IPC - const serverProcess = fork(join(__dirname, '../built/boot/entry.js'), [], { + const serverProcess = fork(join(__dirname, '../built/boot/entry.js'), ['expose-gc'], { cwd: join(__dirname, '..'), env: { ...process.env, - NODE_ENV: 'test', + NODE_ENV: 'production', + MK_DISABLE_CLUSTERING: '1', }, stdio: ['pipe', 'pipe', 'pipe', 'ipc'], + execArgv: [...process.execArgv, '--expose-gc'], }); let serverReady = false; @@ -57,6 +89,40 @@ async function measureMemory() { process.stderr.write(`[server error] ${err}\n`); }); + async function triggerGc() { + const ok = new Promise((resolve) => { + serverProcess.once('message', (message) => { + if (message === 'gc ok') resolve(); + }); + }); + + serverProcess.send('gc'); + + await ok; + + await setTimeout(1000); + } + + function createRequest() { + return new Promise((resolve, reject) => { + const req = http.request({ + host: 'localhost', + port: 61812, + path: '/api/meta', + method: 'POST', + }, (res) => { + res.on('data', () => { }); + res.on('end', () => { + resolve(); + }); + }); + req.on('error', (err) => { + reject(err); + }); + req.end(); + }); + } + // Wait for server to be ready or timeout const startupStartTime = Date.now(); while (!serverReady) { @@ -73,46 +139,23 @@ async function measureMemory() { // Wait for memory to settle await setTimeout(MEMORY_SETTLE_TIME); - // Get memory usage from the server process via /proc const pid = serverProcess.pid; - let memoryInfo; - try { - const fs = await import('node:fs/promises'); + const beforeGc = await getMemoryUsage(pid); - // Read /proc/[pid]/status for detailed memory info - const status = await fs.readFile(`/proc/${pid}/status`, 'utf-8'); - const vmRssMatch = status.match(/VmRSS:\s+(\d+)\s+kB/); - const vmDataMatch = status.match(/VmData:\s+(\d+)\s+kB/); - const vmSizeMatch = status.match(/VmSize:\s+(\d+)\s+kB/); + await triggerGc(); - memoryInfo = { - rss: vmRssMatch ? parseInt(vmRssMatch[1], 10) * 1024 : null, - heapUsed: vmDataMatch ? parseInt(vmDataMatch[1], 10) * 1024 : null, - vmSize: vmSizeMatch ? parseInt(vmSizeMatch[1], 10) * 1024 : null, - }; - } catch (err) { - // Fallback: use ps command - process.stderr.write(`Warning: Could not read /proc/${pid}/status: ${err}\n`); + const afterGc = await getMemoryUsage(pid); - const { execSync } = await import('node:child_process'); - try { - const ps = execSync(`ps -o rss= -p ${pid}`, { encoding: 'utf-8' }); - const rssKb = parseInt(ps.trim(), 10); - memoryInfo = { - rss: rssKb * 1024, - heapUsed: null, - vmSize: null, - }; - } catch { - memoryInfo = { - rss: null, - heapUsed: null, - vmSize: null, - error: 'Could not measure memory', - }; - } - } + // create some http requests to simulate load + const REQUEST_COUNT = 10; + await Promise.all( + Array.from({ length: REQUEST_COUNT }).map(() => createRequest()), + ); + + await triggerGc(); + + const afterRequest = await getMemoryUsage(pid); // Stop the server serverProcess.kill('SIGTERM'); @@ -135,15 +178,51 @@ async function measureMemory() { const result = { timestamp: new Date().toISOString(), - startupTimeMs: startupTime, - memory: memoryInfo, + beforeGc, + afterGc, + afterRequest, + }; + + return result; +} + +async function main() { + // 直列の方が時間的に分散されて正確そうだから直列でやる + const results = []; + for (let i = 0; i < SAMPLE_COUNT; i++) { + const res = await measureMemory(); + results.push(res); + } + + // Calculate averages + const beforeGc = structuredClone(keys); + const afterGc = structuredClone(keys); + const afterRequest = structuredClone(keys); + for (const res of results) { + for (const key of Object.keys(keys)) { + beforeGc[key] += res.beforeGc[key]; + afterGc[key] += res.afterGc[key]; + afterRequest[key] += res.afterRequest[key]; + } + } + for (const key of Object.keys(keys)) { + beforeGc[key] = Math.round(beforeGc[key] / SAMPLE_COUNT); + afterGc[key] = Math.round(afterGc[key] / SAMPLE_COUNT); + afterRequest[key] = Math.round(afterRequest[key] / SAMPLE_COUNT); + } + + const result = { + timestamp: new Date().toISOString(), + beforeGc, + afterGc, + afterRequest, }; // Output as JSON to stdout console.log(JSON.stringify(result, null, 2)); } -measureMemory().catch((err) => { +main().catch((err) => { console.error(JSON.stringify({ error: err.message, timestamp: new Date().toISOString(), diff --git a/packages/backend/scripts/watch.mjs b/packages/backend/scripts/watch.mjs index a0ccea3b16..9d608b233c 100644 --- a/packages/backend/scripts/watch.mjs +++ b/packages/backend/scripts/watch.mjs @@ -21,7 +21,7 @@ import { execa } from 'execa'; }); }, 3000); - execa('tsc', ['-w', '-p', 'tsconfig.json'], { + execa('tsgo', ['-w', '-p', 'tsconfig.json'], { stdout: process.stdout, stderr: process.stderr, }); diff --git a/packages/backend/src/boot/entry.ts b/packages/backend/src/boot/entry.ts index da585ad68d..3a33d198a5 100644 --- a/packages/backend/src/boot/entry.ts +++ b/packages/backend/src/boot/entry.ts @@ -86,6 +86,18 @@ if (!envOption.disableClustering) { ev.mount(); } +process.on('message', msg => { + if (msg === 'gc') { + if (global.gc != null) { + logger.info('Manual GC triggered'); + global.gc(); + if (process.send != null) process.send('gc ok'); + } else { + logger.warn('Manual GC requested but gc is not available. Start the process with --expose-gc to enable this feature.'); + } + } +}); + readyRef.value = true; // ユニットテスト時にMisskeyが子プロセスで起動された時のため diff --git a/packages/backend/src/boot/master.ts b/packages/backend/src/boot/master.ts index 4776d0d412..041f58e509 100644 --- a/packages/backend/src/boot/master.ts +++ b/packages/backend/src/boot/master.ts @@ -4,8 +4,6 @@ */ import * as fs from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { dirname } from 'node:path'; import * as os from 'node:os'; import cluster from 'node:cluster'; import chalk from 'chalk'; @@ -17,20 +15,15 @@ import { showMachineInfo } from '@/misc/show-machine-info.js'; import { envOption } from '@/env.js'; import { jobQueue, server } from './common.js'; -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const meta = JSON.parse(fs.readFileSync(`${_dirname}/../../../../built/meta.json`, 'utf-8')); - const logger = new Logger('core', 'cyan'); const bootLogger = logger.createSubLogger('boot', 'magenta'); const themeColor = chalk.hex('#86b300'); -function greet() { +function greet(props: { version: string }) { if (!envOption.quiet) { //#region Misskey logo - const v = `v${meta.version}`; + const v = `v${props.version}`; console.log(themeColor(' _____ _ _ ')); console.log(themeColor(' | |_|___ ___| |_ ___ _ _ ')); console.log(themeColor(' | | | | |_ -|_ -| \'_| -_| | |')); @@ -46,7 +39,7 @@ function greet() { } bootLogger.info('Welcome to Misskey!'); - bootLogger.info(`Misskey v${meta.version}`, null, true); + bootLogger.info(`Misskey v${props.version}`, null, true); } /** @@ -57,15 +50,15 @@ export async function masterMain() { // initialize app try { - greet(); + config = loadConfigBoot(); + greet({ version: config.version }); showEnvironment(); await showMachineInfo(bootLogger); showNodejsVersion(); - config = loadConfigBoot(); //await connectDb(); if (config.pidFile) fs.writeFileSync(config.pidFile, process.pid.toString()); } catch (e) { - bootLogger.error('Fatal error occurred during initialization', null, true); + bootLogger.error('Fatal error occurred during initialization: ' + e, null, true); process.exit(1); } diff --git a/packages/backend/src/config.ts b/packages/backend/src/config.ts index f9852d3578..6a83359d38 100644 --- a/packages/backend/src/config.ts +++ b/packages/backend/src/config.ts @@ -10,7 +10,6 @@ import { type FastifyServerOptions } from 'fastify'; import type * as Sentry from '@sentry/node'; import type * as SentryVue from '@sentry/vue'; import type { RedisOptions } from 'ioredis'; -import type { ManifestChunk } from 'vite'; type RedisOptionsSource = Partial & { host: string; @@ -30,6 +29,7 @@ type Source = { socket?: string; trustProxy?: FastifyServerOptions['trustProxy']; chmodSocket?: string; + enableIpRateLimit?: boolean; disableHsts?: boolean; db: { host: string; @@ -120,8 +120,9 @@ export type Config = { url: string; port: number; socket: string | undefined; - trustProxy: FastifyServerOptions['trustProxy']; + trustProxy: NonNullable; chmodSocket: string | undefined; + enableIpRateLimit: boolean; disableHsts: boolean | undefined; db: { host: string; @@ -187,9 +188,7 @@ export type Config = { authUrl: string; driveUrl: string; userAgent: string; - frontendEntry: ManifestChunk; frontendManifestExists: boolean; - frontendEmbedEntry: ManifestChunk; frontendEmbedManifestExists: boolean; mediaProxy: string; externalMediaProxyEnabled: boolean; @@ -217,25 +216,37 @@ export type FulltextSearchProvider = 'sqlLike' | 'sqlPgroonga' | 'meilisearch'; const _filename = fileURLToPath(import.meta.url); const _dirname = dirname(_filename); -const compiledConfigFilePathForTest = resolve(_dirname, '../../../built/._config_.json'); +/** Path of repository root directory */ +let rootDir = _dirname; +// 見つかるまで上に遡る +while (!fs.existsSync(resolve(rootDir, 'packages'))) { + const parentDir = dirname(rootDir); + if (parentDir === rootDir) { + throw new Error('Cannot find root directory'); + } + rootDir = parentDir; +} -export const compiledConfigFilePath = fs.existsSync(compiledConfigFilePathForTest) ? compiledConfigFilePathForTest : resolve(_dirname, '../../../built/.config.json'); +/** Path of configuration directory */ +const configDir = resolve(rootDir, '.config'); +/** Path of built directory */ +const projectBuiltDir = resolve(rootDir, 'built'); + +const compiledConfigFilePathForTest = resolve(projectBuiltDir, '._config_.json'); + +export const compiledConfigFilePath = fs.existsSync(compiledConfigFilePathForTest) + ? compiledConfigFilePathForTest + : resolve(projectBuiltDir, '.config.json'); export function loadConfig(): Config { if (!fs.existsSync(compiledConfigFilePath)) { throw new Error('Compiled configuration file not found. Try running \'pnpm compile-config\'.'); } - const meta = JSON.parse(fs.readFileSync(`${_dirname}/../../../built/meta.json`, 'utf-8')); + const meta = JSON.parse(fs.readFileSync(resolve(projectBuiltDir, 'meta.json'), 'utf-8')); - const frontendManifestExists = fs.existsSync(_dirname + '/../../../built/_frontend_vite_/manifest.json'); - const frontendEmbedManifestExists = fs.existsSync(_dirname + '/../../../built/_frontend_embed_vite_/manifest.json'); - const frontendManifest = frontendManifestExists ? - JSON.parse(fs.readFileSync(`${_dirname}/../../../built/_frontend_vite_/manifest.json`, 'utf-8')) - : { 'src/_boot_.ts': { file: null } }; - const frontendEmbedManifest = frontendEmbedManifestExists ? - JSON.parse(fs.readFileSync(`${_dirname}/../../../built/_frontend_embed_vite_/manifest.json`, 'utf-8')) - : { 'src/boot.ts': { file: null } }; + const frontendManifestExists = fs.existsSync(resolve(projectBuiltDir, '_frontend_vite_/manifest.json')); + const frontendEmbedManifestExists = fs.existsSync(resolve(projectBuiltDir, '_frontend_embed_vite_/manifest.json')); const config = JSON.parse(fs.readFileSync(compiledConfigFilePath, 'utf-8')) as Source; @@ -263,9 +274,17 @@ export function loadConfig(): Config { url: url.origin, port: config.port ?? parseInt(process.env.PORT ?? '', 10), socket: config.socket, - trustProxy: config.trustProxy, + trustProxy: config.trustProxy ?? [ + '10.0.0.0/8', + '172.16.0.0/12', + '192.168.0.0/16', + '127.0.0.1/32', + '::1/128', + 'fc00::/7', + ], chmodSocket: config.chmodSocket, disableHsts: config.disableHsts, + enableIpRateLimit: config.enableIpRateLimit ?? true, host, hostname, scheme, @@ -309,9 +328,7 @@ export function loadConfig(): Config { config.videoThumbnailGenerator.endsWith('/') ? config.videoThumbnailGenerator.substring(0, config.videoThumbnailGenerator.length - 1) : config.videoThumbnailGenerator : null, userAgent: `Misskey/${version} (${config.url})`, - frontendEntry: frontendManifest['src/_boot_.ts'], frontendManifestExists: frontendManifestExists, - frontendEmbedEntry: frontendEmbedManifest['src/boot.ts'], frontendEmbedManifestExists: frontendEmbedManifestExists, perChannelMaxNoteCacheCount: config.perChannelMaxNoteCacheCount ?? 1000, perUserNotificationsMaxCount: config.perUserNotificationsMaxCount ?? 500, @@ -324,7 +341,7 @@ export function loadConfig(): Config { function tryCreateUrl(url: string) { try { return new URL(url); - } catch (e) { + } catch (_) { throw new Error(`url="${url}" is not a valid URL.`); } } diff --git a/packages/backend/src/core/AccountMoveService.ts b/packages/backend/src/core/AccountMoveService.ts index f8e3eaf01f..5d668bc582 100644 --- a/packages/backend/src/core/AccountMoveService.ts +++ b/packages/backend/src/core/AccountMoveService.ts @@ -75,7 +75,7 @@ export class AccountMoveService { */ @bindThis public async moveFromLocal(src: MiLocalUser, dst: MiLocalUser | MiRemoteUser): Promise { - const srcUri = this.userEntityService.getUserUri(src); + const _srcUri = this.userEntityService.getUserUri(src); const dstUri = this.userEntityService.getUserUri(dst); // add movedToUri to indicate that the user has moved diff --git a/packages/backend/src/core/AiService.ts b/packages/backend/src/core/AiService.ts index 7a005400bb..7d60995a7d 100644 --- a/packages/backend/src/core/AiService.ts +++ b/packages/backend/src/core/AiService.ts @@ -7,11 +7,10 @@ import * as fs from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; import { Injectable } from '@nestjs/common'; -import si from 'systeminformation'; import { Mutex } from 'async-mutex'; import fetch from 'node-fetch'; import { bindThis } from '@/decorators.js'; -import type { NSFWJS, PredictionType } from 'nsfwjs'; +import type { NSFWJS, PredictionType } from 'nsfwjs/core'; const _filename = fileURLToPath(import.meta.url); const _dirname = dirname(_filename); @@ -44,7 +43,7 @@ export class AiService { tf.env().global.fetch = fetch; if (this.model == null) { - const nsfw = await import('nsfwjs'); + const nsfw = await import('nsfwjs/core'); await this.modelLoadMutex.runExclusive(async () => { if (this.model == null) { this.model = await nsfw.load(`file://${_dirname}/../../nsfw-model/`, { size: 299 }); @@ -84,6 +83,7 @@ export class AiService { @bindThis private async getCpuFlags(): Promise { + const si = await import('systeminformation'); const str = await si.cpuFlags(); return str.split(/\s+/); } diff --git a/packages/backend/src/core/AnnouncementService.ts b/packages/backend/src/core/AnnouncementService.ts index a9f6731977..f750ca212a 100644 --- a/packages/backend/src/core/AnnouncementService.ts +++ b/packages/backend/src/core/AnnouncementService.ts @@ -205,7 +205,7 @@ export class AnnouncementService { announcementId: announcementId, userId: user.id, }); - } catch (e) { + } catch (_) { return; } diff --git a/packages/backend/src/core/AvatarDecorationService.ts b/packages/backend/src/core/AvatarDecorationService.ts index 4efd6122b1..70a50a0175 100644 --- a/packages/backend/src/core/AvatarDecorationService.ts +++ b/packages/backend/src/core/AvatarDecorationService.ts @@ -39,7 +39,7 @@ export class AvatarDecorationService implements OnApplicationShutdown { const obj = JSON.parse(data); if (obj.channel === 'internal') { - const { type, body } = obj.message as GlobalEvents['internal']['payload']; + const { type, body: _ } = obj.message as GlobalEvents['internal']['payload']; switch (type) { case 'avatarDecorationCreated': case 'avatarDecorationUpdated': diff --git a/packages/backend/src/core/CoreModule.ts b/packages/backend/src/core/CoreModule.ts index 87575ca59a..f075671d93 100644 --- a/packages/backend/src/core/CoreModule.ts +++ b/packages/backend/src/core/CoreModule.ts @@ -141,7 +141,7 @@ import { ApLoggerService } from './activitypub/ApLoggerService.js'; 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 { ApResolverService, Resolver } from './activitypub/ApResolverService.js'; import { JsonLdService } from './activitypub/JsonLdService.js'; import { RemoteLoggerService } from './RemoteLoggerService.js'; import { RemoteUserResolveService } from './RemoteUserResolveService.js'; @@ -447,6 +447,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ApRendererService, ApRequestService, ApResolverService, + Resolver, JsonLdService, RemoteLoggerService, RemoteUserResolveService, @@ -745,6 +746,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting ApRendererService, ApRequestService, ApResolverService, + Resolver, JsonLdService, RemoteLoggerService, RemoteUserResolveService, diff --git a/packages/backend/src/core/EmailService.ts b/packages/backend/src/core/EmailService.ts index c7be0f7843..384704b252 100644 --- a/packages/backend/src/core/EmailService.ts +++ b/packages/backend/src/core/EmailService.ts @@ -366,7 +366,7 @@ export class EmailService { valid: true, reason: null, }; - } catch (error) { + } catch (_) { return { valid: false, reason: 'network', diff --git a/packages/backend/src/core/FileInfoService.ts b/packages/backend/src/core/FileInfoService.ts index af4d0b8c6b..c7c9f8037d 100644 --- a/packages/backend/src/core/FileInfoService.ts +++ b/packages/backend/src/core/FileInfoService.ts @@ -484,25 +484,13 @@ export class FileInfoService { * Calculate blurhash string of image */ @bindThis - private getBlurhash(path: string, type: string): Promise { - return new Promise(async (resolve, reject) => { - (await sharpBmp(path, type)) - .raw() - .ensureAlpha() - .resize(64, 64, { fit: 'inside' }) - .toBuffer((err, buffer, info) => { - if (err) return reject(err); - - let hash; - - try { - hash = blurhash.encode(new Uint8ClampedArray(buffer), info.width, info.height, 5, 5); - } catch (e) { - return reject(e); - } - - resolve(hash); - }); - }); + private async getBlurhash(path: string, type: string): Promise { + const sharp = await sharpBmp(path, type); + const { data: buffer, info } = await sharp + .raw() + .ensureAlpha() + .resize(64, 64, { fit: 'inside' }) + .toBuffer({ resolveWithObject: true }); + return blurhash.encode(new Uint8ClampedArray(buffer), info.width, info.height, 5, 5); } } diff --git a/packages/backend/src/core/GlobalEventService.ts b/packages/backend/src/core/GlobalEventService.ts index f4c747b139..5fe50e5e64 100644 --- a/packages/backend/src/core/GlobalEventService.ts +++ b/packages/backend/src/core/GlobalEventService.ts @@ -38,11 +38,7 @@ export interface BroadcastTypes { emojis: Packed<'EmojiDetailed'>[]; }; emojiDeleted: { - emojis: { - id?: string; - name: string; - [other: string]: any; - }[]; + emojis: Packed<'EmojiDetailed'>[]; }; announcementCreated: { announcement: Packed<'Announcement'>; @@ -133,6 +129,9 @@ export interface NoteEventTypes { type NoteStreamEventTypes = { [key in keyof NoteEventTypes]: { id: MiNote['id']; + userId: MiNote['userId']; + visibility: MiNote['visibility']; + visibleUserIds: MiNote['visibleUserIds']; body: NoteEventTypes[key]; }; }; @@ -382,9 +381,12 @@ export class GlobalEventService { } @bindThis - public publishNoteStream(noteId: MiNote['id'], type: K, value?: NoteEventTypes[K]): void { - this.publish(`noteStream:${noteId}`, type, { - id: noteId, + public publishNoteStream(note: MiNote, type: K, value?: NoteEventTypes[K]): void { + this.publish(`noteStream:${note.id}`, type, { + id: note.id, + userId: note.userId, + visibility: note.visibility, + visibleUserIds: note.visibleUserIds, body: value, }); } diff --git a/packages/backend/src/core/MfmService.ts b/packages/backend/src/core/MfmService.ts index b9f1c62d9d..274966d921 100644 --- a/packages/backend/src/core/MfmService.ts +++ b/packages/backend/src/core/MfmService.ts @@ -308,7 +308,7 @@ export class MfmService { try { const date = new Date(parseInt(text, 10) * 1000); return ``; - } catch (err) { + } catch (_) { return fnDefault(node); } } @@ -376,7 +376,7 @@ export class MfmService { try { const url = new URL(node.props.url); return `${toHtml(node.children)}`; - } catch (err) { + } catch (_) { return `[${toHtml(node.children)}](${escapeHtml(node.props.url)})`; } }, @@ -390,7 +390,7 @@ export class MfmService { try { const url = new URL(href); return `${escapeHtml(acct)}`; - } catch (err) { + } catch (_) { return escapeHtml(acct); } }, @@ -419,7 +419,7 @@ export class MfmService { try { const url = new URL(node.props.url); return `${escapeHtml(node.props.url)}`; - } catch (err) { + } catch (_) { return escapeHtml(node.props.url); } }, diff --git a/packages/backend/src/core/NoteDeleteService.ts b/packages/backend/src/core/NoteDeleteService.ts index af1f0eda9a..1b945277b7 100644 --- a/packages/backend/src/core/NoteDeleteService.ts +++ b/packages/backend/src/core/NoteDeleteService.ts @@ -68,7 +68,7 @@ export class NoteDeleteService { } if (!quiet) { - this.globalEventService.publishNoteStream(note.id, 'deleted', { + this.globalEventService.publishNoteStream(note, 'deleted', { deletedAt: deletedAt, }); diff --git a/packages/backend/src/core/NoteDraftService.ts b/packages/backend/src/core/NoteDraftService.ts index a346ff7618..e144138c2c 100644 --- a/packages/backend/src/core/NoteDraftService.ts +++ b/packages/backend/src/core/NoteDraftService.ts @@ -187,9 +187,9 @@ export class NoteDraftService { } //#region visibleUsers - let visibleUsers: MiUser[] = []; + let _visibleUsers: MiUser[] = []; if (data.visibleUserIds != null && data.visibleUserIds.length > 0) { - visibleUsers = await this.usersRepository.findBy({ + _visibleUsers = await this.usersRepository.findBy({ id: In(data.visibleUserIds), }); } diff --git a/packages/backend/src/core/PollService.ts b/packages/backend/src/core/PollService.ts index 6c96ab16cf..d21a43714f 100644 --- a/packages/backend/src/core/PollService.ts +++ b/packages/backend/src/core/PollService.ts @@ -83,7 +83,7 @@ export class PollService { const index = choice + 1; // In SQL, array index is 1 based await this.pollsRepository.query(`UPDATE poll SET votes[${index}] = votes[${index}] + 1 WHERE "noteId" = '${poll.noteId}'`); - this.globalEventService.publishNoteStream(note.id, 'pollVoted', { + this.globalEventService.publishNoteStream(note, 'pollVoted', { choice: choice, userId: user.id, }); diff --git a/packages/backend/src/core/QueryService.ts b/packages/backend/src/core/QueryService.ts index 49f93ad108..34810059da 100644 --- a/packages/backend/src/core/QueryService.ts +++ b/packages/backend/src/core/QueryService.ts @@ -259,7 +259,7 @@ export class QueryService { @bindThis public generateVisibilityQuery(q: SelectQueryBuilder, me?: { id: MiUser['id'] } | null): void { - // This code must always be synchronized with the checks in Notes.isVisibleForMe. + // This code must always be synchronized with the checks in NoteEntityService.isVisibleForMe and Stream abstract class Channel.isNoteVisibleForMe. if (me == null) { q.andWhere(new Brackets(qb => { qb diff --git a/packages/backend/src/core/QueueService.ts b/packages/backend/src/core/QueueService.ts index 42782167bb..f90ae80731 100644 --- a/packages/backend/src/core/QueueService.ts +++ b/packages/backend/src/core/QueueService.ts @@ -6,7 +6,6 @@ import { randomUUID } from 'node:crypto'; import { Inject, Injectable } from '@nestjs/common'; import { MetricsTime, type JobType } from 'bullmq'; -import { parse as parseRedisInfo } from 'redis-info'; import type { IActivity } from '@/core/activitypub/type.js'; import type { MiDriveFile } from '@/models/DriveFile.js'; import type { MiWebhook, WebhookEventTypes } from '@/models/Webhook.js'; @@ -86,6 +85,19 @@ const REPEATABLE_SYSTEM_JOB_DEF = [{ pattern: '0 4 * * *', }]; +function parseRedisInfo(infoText: string): Record { + const fields = infoText + .split('\n') + .filter(line => line.length > 0 && !line.startsWith('#')) + .map(line => line.trim().split(':')); + + const result: Record = {}; + for (const [key, value] of fields) { + result[key] = value; + } + return result; +} + @Injectable() export class QueueService { constructor( @@ -890,7 +902,7 @@ export class QueueService { }, db: { version: db.redis_version, - mode: db.redis_mode, + mode: db.redis_mode as 'cluster' | 'standalone' | 'sentinel', runId: db.run_id, processId: db.process_id, port: parseInt(db.tcp_port), diff --git a/packages/backend/src/core/ReactionService.ts b/packages/backend/src/core/ReactionService.ts index 6f9fe53937..cd1e87dbd8 100644 --- a/packages/backend/src/core/ReactionService.ts +++ b/packages/backend/src/core/ReactionService.ts @@ -244,7 +244,7 @@ export class ReactionService { }, }); - this.globalEventService.publishNoteStream(note.id, 'reacted', { + this.globalEventService.publishNoteStream(note, 'reacted', { reaction: decodedReaction.reaction, emoji: customEmoji != null ? { name: customEmoji.host ? `${customEmoji.name}@${customEmoji.host}` : `${customEmoji.name}@.`, @@ -318,7 +318,7 @@ export class ReactionService { .execute(); } - this.globalEventService.publishNoteStream(note.id, 'unreacted', { + this.globalEventService.publishNoteStream(note, 'unreacted', { reaction: this.decodeReaction(exist.reaction).reaction, userId: user.id, }); diff --git a/packages/backend/src/core/RoleService.ts b/packages/backend/src/core/RoleService.ts index f2f7480dfa..2ffee69c21 100644 --- a/packages/backend/src/core/RoleService.ts +++ b/packages/backend/src/core/RoleService.ts @@ -314,7 +314,7 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit { default: return false; } - } catch (err) { + } catch (_) { // TODO: log error return false; } diff --git a/packages/backend/src/core/SearchService.ts b/packages/backend/src/core/SearchService.ts index 7077e6f63a..9ea6a27295 100644 --- a/packages/backend/src/core/SearchService.ts +++ b/packages/backend/src/core/SearchService.ts @@ -190,8 +190,7 @@ export class SearchService { return this.searchNoteByMeiliSearch(q, me, opts, pagination); } default: { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const typeCheck: never = this.provider; + const _: never = this.provider; return []; } } diff --git a/packages/backend/src/core/UserSuspendService.ts b/packages/backend/src/core/UserSuspendService.ts index 7920e58e36..3ecb912a64 100644 --- a/packages/backend/src/core/UserSuspendService.ts +++ b/packages/backend/src/core/UserSuspendService.ts @@ -49,8 +49,8 @@ export class UserSuspendService { }); (async () => { - await this.postSuspend(user).catch(e => {}); - await this.unFollowAll(user).catch(e => {}); + await this.postSuspend(user).catch(_ => {}); + await this.unFollowAll(user).catch(_ => {}); })(); } @@ -67,7 +67,7 @@ export class UserSuspendService { }); (async () => { - await this.postUnsuspend(user).catch(e => {}); + await this.postUnsuspend(user).catch(_ => {}); })(); } diff --git a/packages/backend/src/core/UtilityService.ts b/packages/backend/src/core/UtilityService.ts index 21ea9b9983..e3ceebccae 100644 --- a/packages/backend/src/core/UtilityService.ts +++ b/packages/backend/src/core/UtilityService.ts @@ -98,7 +98,7 @@ export class UtilityService { try { // TODO: RE2インスタンスをキャッシュ return new RE2(regexp[1], regexp[2]).test(text); - } catch (err) { + } catch (_) { // This should never happen due to input sanitisation. return false; } diff --git a/packages/backend/src/core/activitypub/ApInboxService.ts b/packages/backend/src/core/activitypub/ApInboxService.ts index 81637580e3..ff47ca930d 100644 --- a/packages/backend/src/core/activitypub/ApInboxService.ts +++ b/packages/backend/src/core/activitypub/ApInboxService.ts @@ -95,7 +95,7 @@ export class ApInboxService { if (isCollectionOrOrderedCollection(activity)) { const results = [] as [string, string | void][]; // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const items = toArray(isCollection(activity) ? activity.items : activity.orderedItems); if (items.length >= resolver.getRecursionLimit()) { @@ -221,7 +221,7 @@ export class ApInboxService { this.logger.info(`Accept: ${uri}`); // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const object = await resolver.resolve(activity.object).catch(err => { this.logger.error(`Resolution failed: ${err}`); @@ -284,7 +284,7 @@ export class ApInboxService { this.logger.info(`Announce: ${uri}`); // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); if (!activity.object) return 'skip: activity has no object property'; const targetUri = getApId(activity.object); @@ -406,7 +406,7 @@ export class ApInboxService { } // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const object = await resolver.resolve(activity.object).catch(e => { this.logger.error(`Resolution failed: ${e}`); @@ -575,7 +575,7 @@ export class ApInboxService { this.logger.info(`Reject: ${uri}`); // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const object = await resolver.resolve(activity.object).catch(e => { this.logger.error(`Resolution failed: ${e}`); @@ -642,7 +642,7 @@ export class ApInboxService { this.logger.info(`Undo: ${uri}`); // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const object = await resolver.resolve(activity.object).catch(e => { this.logger.error(`Resolution failed: ${e}`); @@ -774,7 +774,7 @@ export class ApInboxService { this.logger.debug('Update'); // eslint-disable-next-line no-param-reassign - resolver ??= this.apResolverService.createResolver(); + resolver ??= await this.apResolverService.createResolver(); const object = await resolver.resolve(activity.object).catch(e => { this.logger.error(`Resolution failed: ${e}`); diff --git a/packages/backend/src/core/activitypub/ApRendererService.ts b/packages/backend/src/core/activitypub/ApRendererService.ts index 4570977c5d..8c461b6031 100644 --- a/packages/backend/src/core/activitypub/ApRendererService.ts +++ b/packages/backend/src/core/activitypub/ApRendererService.ts @@ -515,7 +515,7 @@ export class ApRendererService { const restPart = maybeUrl.slice(match[0].length); return `${urlPart}${restPart}`; - } catch (e) { + } catch (_) { return maybeUrl; } }; diff --git a/packages/backend/src/core/activitypub/ApRequestService.ts b/packages/backend/src/core/activitypub/ApRequestService.ts index 49298a1d22..0ad885a17c 100644 --- a/packages/backend/src/core/activitypub/ApRequestService.ts +++ b/packages/backend/src/core/activitypub/ApRequestService.ts @@ -81,7 +81,7 @@ export class ApRequestCreator { }, args.additionalHeaders), }; - const result = this.#signToRequest(request, args.key, ['(request-target)', 'date', 'host', 'accept']); + const result = this.#signToRequest(request, args.key, ['(request-target)', 'date', 'host']); return { request, @@ -226,7 +226,7 @@ export class ApRequestService { return await this.signedGet(href, user, allowSoftfail, false); } } - } catch (e) { + } catch (_) { // something went wrong parsing the HTML, ignore the whole thing } } diff --git a/packages/backend/src/core/activitypub/ApResolverService.ts b/packages/backend/src/core/activitypub/ApResolverService.ts index 646150455b..0f51b1ce8d 100644 --- a/packages/backend/src/core/activitypub/ApResolverService.ts +++ b/packages/backend/src/core/activitypub/ApResolverService.ts @@ -3,10 +3,17 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Inject, Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { IsNull, Not } from 'typeorm'; import type { MiLocalUser, MiRemoteUser } from '@/models/User.js'; -import type { NotesRepository, PollsRepository, NoteReactionsRepository, UsersRepository, FollowRequestsRepository, MiMeta } from '@/models/_.js'; +import type { + FollowRequestsRepository, + MiMeta, + NoteReactionsRepository, + NotesRepository, + PollsRepository, + UsersRepository +} from '@/models/_.js'; import type { Config } from '@/config.js'; import { HttpRequestService } from '@/core/HttpRequestService.js'; import { DI } from '@/di-symbols.js'; @@ -16,26 +23,43 @@ import { LoggerService } from '@/core/LoggerService.js'; import type Logger from '@/logger.js'; import { SystemAccountService } from '@/core/SystemAccountService.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; +import type { ICollection, IObject, IOrderedCollection } from './type.js'; import { isCollectionOrOrderedCollection } from './type.js'; import { ApDbResolverService } from './ApDbResolverService.js'; import { ApRendererService } from './ApRendererService.js'; import { ApRequestService } from './ApRequestService.js'; import { FetchAllowSoftFailMask } from './misc/check-against-url.js'; -import type { IObject, ICollection, IOrderedCollection } from './type.js'; +import { ModuleRef } from '@nestjs/core'; +@Injectable({ scope: Scope.TRANSIENT }) export class Resolver { private history: Set; private user?: MiLocalUser; private logger: Logger; + private recursionLimit = 256; constructor( + @Inject(DI.config) private config: Config, + + @Inject(DI.meta) private meta: MiMeta, + + @Inject(DI.usersRepository) private usersRepository: UsersRepository, + + @Inject(DI.notesRepository) private notesRepository: NotesRepository, + + @Inject(DI.pollsRepository) private pollsRepository: PollsRepository, + + @Inject(DI.noteReactionsRepository) private noteReactionsRepository: NoteReactionsRepository, + + @Inject(DI.followRequestsRepository) private followRequestsRepository: FollowRequestsRepository, + private utilityService: UtilityService, private systemAccountService: SystemAccountService, private apRequestService: ApRequestService, @@ -43,7 +67,6 @@ export class Resolver { private apRendererService: ApRendererService, private apDbResolverService: ApDbResolverService, private loggerService: LoggerService, - private recursionLimit = 256, ) { this.history = new Set(); this.logger = this.loggerService.getLogger('ap-resolve'); @@ -180,54 +203,12 @@ export class Resolver { @Injectable() export class ApResolverService { constructor( - @Inject(DI.config) - private config: Config, - - @Inject(DI.meta) - private meta: MiMeta, - - @Inject(DI.usersRepository) - private usersRepository: UsersRepository, - - @Inject(DI.notesRepository) - private notesRepository: NotesRepository, - - @Inject(DI.pollsRepository) - private pollsRepository: PollsRepository, - - @Inject(DI.noteReactionsRepository) - private noteReactionsRepository: NoteReactionsRepository, - - @Inject(DI.followRequestsRepository) - private followRequestsRepository: FollowRequestsRepository, - - private utilityService: UtilityService, - private systemAccountService: SystemAccountService, - private apRequestService: ApRequestService, - private httpRequestService: HttpRequestService, - private apRendererService: ApRendererService, - private apDbResolverService: ApDbResolverService, - private loggerService: LoggerService, + private moduleRef: ModuleRef, ) { } @bindThis - public createResolver(): Resolver { - return new Resolver( - this.config, - this.meta, - this.usersRepository, - this.notesRepository, - this.pollsRepository, - this.noteReactionsRepository, - this.followRequestsRepository, - this.utilityService, - this.systemAccountService, - this.apRequestService, - this.httpRequestService, - this.apRendererService, - this.apDbResolverService, - this.loggerService, - ); + public async createResolver(): Promise { + return await this.moduleRef.create(Resolver); } } diff --git a/packages/backend/src/core/activitypub/models/ApImageService.ts b/packages/backend/src/core/activitypub/models/ApImageService.ts index e7ece87b01..0496774c19 100644 --- a/packages/backend/src/core/activitypub/models/ApImageService.ts +++ b/packages/backend/src/core/activitypub/models/ApImageService.ts @@ -46,7 +46,7 @@ export class ApImageService { throw new Error('actor has been suspended'); } - const image = await this.apResolverService.createResolver().resolve(value); + const image = await (await this.apResolverService.createResolver()).resolve(value); if (!isDocument(image)) return null; diff --git a/packages/backend/src/core/activitypub/models/ApNoteService.ts b/packages/backend/src/core/activitypub/models/ApNoteService.ts index 214d32f67f..1fc5728c98 100644 --- a/packages/backend/src/core/activitypub/models/ApNoteService.ts +++ b/packages/backend/src/core/activitypub/models/ApNoteService.ts @@ -128,7 +128,7 @@ export class ApNoteService { @bindThis public async createNote(value: string | IObject, actor?: MiRemoteUser, resolver?: Resolver, silent = false): Promise { // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); const object = await resolver.resolve(value); diff --git a/packages/backend/src/core/activitypub/models/ApPersonService.ts b/packages/backend/src/core/activitypub/models/ApPersonService.ts index e52078ed0f..ebe8e9c964 100644 --- a/packages/backend/src/core/activitypub/models/ApPersonService.ts +++ b/packages/backend/src/core/activitypub/models/ApPersonService.ts @@ -310,7 +310,7 @@ export class ApPersonService implements OnModuleInit { } // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); const object = await resolver.resolve(uri); if (object.id == null) throw new Error('invalid object.id: ' + object.id); @@ -500,7 +500,7 @@ export class ApPersonService implements OnModuleInit { //#endregion // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); const object = hint ?? await resolver.resolve(uri); @@ -678,7 +678,7 @@ export class ApPersonService implements OnModuleInit { // リモートサーバーからフェッチしてきて登録 // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); return await this.createPerson(uri, resolver); } @@ -707,7 +707,7 @@ export class ApPersonService implements OnModuleInit { this.logger.info(`Updating the featured: ${user.uri}`); - const _resolver = resolver ?? this.apResolverService.createResolver(); + const _resolver = resolver ?? await this.apResolverService.createResolver(); // Resolve to (Ordered)Collection Object const collection = await _resolver.resolveCollection(user.featured); diff --git a/packages/backend/src/core/activitypub/models/ApQuestionService.ts b/packages/backend/src/core/activitypub/models/ApQuestionService.ts index a2cdaf02ca..8ac2f21e26 100644 --- a/packages/backend/src/core/activitypub/models/ApQuestionService.ts +++ b/packages/backend/src/core/activitypub/models/ApQuestionService.ts @@ -45,7 +45,7 @@ export class ApQuestionService { @bindThis public async extractPollFromQuestion(source: string | IObject, resolver?: Resolver): Promise { // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); const question = await resolver.resolve(source); if (!isQuestion(question)) throw new Error('invalid type'); @@ -91,7 +91,7 @@ export class ApQuestionService { // resolve new Question object // eslint-disable-next-line no-param-reassign - if (resolver == null) resolver = this.apResolverService.createResolver(); + if (resolver == null) resolver = await this.apResolverService.createResolver(); const question = await resolver.resolve(value); this.logger.debug(`fetched question: ${JSON.stringify(question, null, 2)}`); diff --git a/packages/backend/src/core/entities/ChatEntityService.ts b/packages/backend/src/core/entities/ChatEntityService.ts index cfa983e766..f69a484398 100644 --- a/packages/backend/src/core/entities/ChatEntityService.ts +++ b/packages/backend/src/core/entities/ChatEntityService.ts @@ -138,7 +138,7 @@ export class ChatEntityService { const reactions: { reaction: string; }[] = []; for (const record of message.reactions) { - const [userId, reaction] = record.split('/'); + const [, reaction] = record.split('/'); reactions.push({ reaction, }); diff --git a/packages/backend/src/core/entities/DriveFileEntityService.ts b/packages/backend/src/core/entities/DriveFileEntityService.ts index a6f7f369a6..1865d494c4 100644 --- a/packages/backend/src/core/entities/DriveFileEntityService.ts +++ b/packages/backend/src/core/entities/DriveFileEntityService.ts @@ -17,6 +17,7 @@ import { deepClone } from '@/misc/clone.js'; import { bindThis } from '@/decorators.js'; import { isMimeImage } from '@/misc/is-mime-image.js'; import { IdService } from '@/core/IdService.js'; +import { uniqueByKey } from '@/misc/unique-by-key.js'; import { UtilityService } from '../UtilityService.js'; import { VideoProcessingService } from '../VideoProcessingService.js'; import { UserEntityService } from './UserEntityService.js'; @@ -226,6 +227,7 @@ export class DriveFileEntityService { options?: PackOptions, hint?: { packedUser?: Packed<'UserLite'> + packedFolder?: Packed<'DriveFolder'> }, ): Promise | null> { const opts = Object.assign({ @@ -250,9 +252,9 @@ export class DriveFileEntityService { thumbnailUrl: this.getThumbnailUrl(file), comment: file.comment, folderId: file.folderId, - folder: opts.detail && file.folderId ? this.driveFolderEntityService.pack(file.folderId, { + folder: opts.detail && file.folderId ? (hint?.packedFolder ?? this.driveFolderEntityService.pack(file.folderId, { detail: true, - }) : null, + })) : null, userId: file.userId, user: (opts.withUser && file.userId) ? hint?.packedUser ?? this.userEntityService.pack(file.userId) : null, }); @@ -263,10 +265,41 @@ export class DriveFileEntityService { files: MiDriveFile[], options?: PackOptions, ): Promise[]> { - const _user = files.map(({ user, userId }) => user ?? userId).filter(x => x != null); - 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) } : {}))); + // -- ユーザ情報の事前取得 -- + + let userMap: Map> | null = null; + if (options?.withUser) { + const users = files + .map(({ user, userId }) => user ?? userId) + .filter(x => x != null); + + const uniqueUsers = uniqueByKey(users, (user) => typeof user === 'string' ? user : user.id); + const packedUsers = await this.userEntityService.packMany(uniqueUsers); + userMap = new Map(packedUsers.map(user => [user.id, user])); + } + + // -- フォルダ情報の事前取得 -- + + let folderMap: Map> | null = null; + if (options?.detail) { + const folders = files + .map(({ folder, folderId }) => folder ?? folderId) + .filter(x => x != null); + + const uniqueFolders = uniqueByKey(folders, (folder) => typeof folder === 'string' ? folder : folder.id); + const packedFolders = await this.driveFolderEntityService.packMany(uniqueFolders, { detail: true }); + folderMap = new Map(packedFolders.map(folder => [folder.id, folder])); + } + + const items = await Promise.all(files.map(f => this.packNullable( + f, + options, + { + packedUser: f.userId ? userMap?.get(f.userId) : undefined, + packedFolder: f.folderId ? folderMap?.get(f.folderId) : undefined, + }, + ))); + return items.filter(x => x != null); } diff --git a/packages/backend/src/core/entities/DriveFolderEntityService.ts b/packages/backend/src/core/entities/DriveFolderEntityService.ts index 299f23ad38..326421e149 100644 --- a/packages/backend/src/core/entities/DriveFolderEntityService.ts +++ b/packages/backend/src/core/entities/DriveFolderEntityService.ts @@ -12,6 +12,9 @@ import type { } from '@/models/Blocking.js'; import type { MiDriveFolder } from '@/models/DriveFolder.js'; import { bindThis } from '@/decorators.js'; import { IdService } from '@/core/IdService.js'; +import { In } from 'typeorm'; +import { uniqueByKey } from '@/misc/unique-by-key.js'; +import { splitIdAndObjects } from '@/misc/split-id-and-objects.js'; @Injectable() export class DriveFolderEntityService { @@ -32,12 +35,20 @@ export class DriveFolderEntityService { options?: { detail: boolean }, + hint?: { + folderMap?: Map; + foldersCountMap?: Map | null; + filesCountMap?: Map | null; + parentPacker?: (id: string) => Promise>; + }, ): Promise> { const opts = Object.assign({ detail: false, }, options); - const folder = typeof src === 'object' ? src : await this.driveFoldersRepository.findOneByOrFail({ id: src }); + const folder = typeof src === 'object' + ? src + : hint?.folderMap?.get(src) ?? await this.driveFoldersRepository.findOneByOrFail({ id: src }); return await awaitAll({ id: folder.id, @@ -46,20 +57,141 @@ export class DriveFolderEntityService { parentId: folder.parentId, ...(opts.detail ? { - foldersCount: this.driveFoldersRepository.countBy({ - parentId: folder.id, - }), - filesCount: this.driveFilesRepository.countBy({ - folderId: folder.id, - }), + foldersCount: hint?.foldersCountMap?.get(folder.id) + ?? this.driveFoldersRepository.countBy({ + parentId: folder.id, + }), + filesCount: hint?.filesCountMap?.get(folder.id) + ?? this.driveFilesRepository.countBy({ + folderId: folder.id, + }), ...(folder.parentId ? { - parent: this.pack(folder.parentId, { - detail: true, - }), + parent: hint?.parentPacker + ? hint.parentPacker(folder.parentId) + : this.pack(folder.parentId, { detail: true }, hint), } : {}), } : {}), }); } -} + public async packMany( + src: Array, + options?: { + detail: boolean + }, + ): Promise>> { + /** + * 重複を除去しつつ、必要なDriveFolderオブジェクトをすべて取得する + */ + const collectUniqueObjects = async (src: Array) => { + const uniqueSrc = uniqueByKey( + src, + (s) => typeof s === 'string' ? s : s.id, + ); + const { ids, objects } = splitIdAndObjects(uniqueSrc); + + const uniqueObjects = new Map(objects.map(s => [s.id, s])); + const needsFetchIds = ids.filter(id => !uniqueObjects.has(id)); + + if (needsFetchIds.length > 0) { + const fetchedObjects = await this.driveFoldersRepository.find({ + where: { + id: In(needsFetchIds), + }, + }); + for (const obj of fetchedObjects) { + uniqueObjects.set(obj.id, obj); + } + } + + return uniqueObjects; + }; + + /** + * 親フォルダーを再帰的に収集する + */ + const collectAncestors = async (folderMap: Map) => { + for (;;) { + const parentIds = new Set(); + for (const folder of folderMap.values()) { + if (folder.parentId != null && !folderMap.has(folder.parentId)) { + parentIds.add(folder.parentId); + } + } + + if (parentIds.size === 0) break; + + const fetchedParents = await this.driveFoldersRepository.find({ + where: { + id: In([...parentIds]), + }, + }); + + if (fetchedParents.length === 0) break; + + for (const parent of fetchedParents) { + folderMap.set(parent.id, parent); + } + } + }; + + const opts = Object.assign({ + detail: false, + }, options); + + const folderMap = await collectUniqueObjects(src); + + let foldersCountMap: Map | null = null; + let filesCountMap: Map | null = null; + if (opts.detail) { + await collectAncestors(folderMap); + + const ids = [...folderMap.keys()]; + if (ids.length > 0) { + const folderCounts = await this.driveFoldersRepository.createQueryBuilder('folder') + .select('folder.parentId', 'parentId') + .addSelect('COUNT(*)', 'count') + .where('folder.parentId IN (:...ids)', { ids }) + .groupBy('folder.parentId') + .getRawMany<{ parentId: string; count: string }>(); + + const fileCounts = await this.driveFilesRepository.createQueryBuilder('file') + .select('file.folderId', 'folderId') + .addSelect('COUNT(*)', 'count') + .where('file.folderId IN (:...ids)', { ids }) + .groupBy('file.folderId') + .getRawMany<{ folderId: string; count: string }>(); + + foldersCountMap = new Map(folderCounts.map(row => [row.parentId, Number(row.count)])); + filesCountMap = new Map(fileCounts.map(row => [row.folderId, Number(row.count)])); + } else { + foldersCountMap = new Map(); + filesCountMap = new Map(); + } + } + + const packedMap = new Map>>(); + const packFromId = (id: string): Promise> => { + const cached = packedMap.get(id); + if (cached) return cached; + + const folder = folderMap.get(id); + if (!folder) { + throw new Error(`DriveFolder not found: ${id}`); + } + + const packedPromise = this.pack(folder, options, { + folderMap, + foldersCountMap, + filesCountMap, + parentPacker: packFromId, + }); + packedMap.set(id, packedPromise); + + return packedPromise; + }; + + return Promise.all(src.map(s => packFromId(typeof s === 'string' ? s : s.id))); + } +} diff --git a/packages/backend/src/core/entities/EmojiEntityService.ts b/packages/backend/src/core/entities/EmojiEntityService.ts index 490d3f2511..309de3b08f 100644 --- a/packages/backend/src/core/entities/EmojiEntityService.ts +++ b/packages/backend/src/core/entities/EmojiEntityService.ts @@ -41,7 +41,7 @@ export class EmojiEntityService { @bindThis public packSimpleMany( - emojis: any[], + emojis: (MiEmoji['id'] | MiEmoji)[], ) { return Promise.all(emojis.map(x => this.packSimple(x))); } @@ -69,7 +69,7 @@ export class EmojiEntityService { @bindThis public packDetailedMany( - emojis: any[], + emojis: (MiEmoji['id'] | MiEmoji)[], ): Promise[]> { return Promise.all(emojis.map(x => this.packDetailed(x))); } diff --git a/packages/backend/src/core/entities/MetaEntityService.ts b/packages/backend/src/core/entities/MetaEntityService.ts index 2da614a120..8e56ddbc02 100644 --- a/packages/backend/src/core/entities/MetaEntityService.ts +++ b/packages/backend/src/core/entities/MetaEntityService.ts @@ -55,13 +55,13 @@ export class MetaEntityService { if (instance.defaultLightTheme) { try { defaultLightTheme = JSON.stringify(JSON5.parse(instance.defaultLightTheme)); - } catch (e) { + } catch (_) { } } if (instance.defaultDarkTheme) { try { defaultDarkTheme = JSON.stringify(JSON5.parse(instance.defaultDarkTheme)); - } catch (e) { + } catch (_) { } } diff --git a/packages/backend/src/core/entities/NoteEntityService.ts b/packages/backend/src/core/entities/NoteEntityService.ts index e7847ba74e..26830c31d0 100644 --- a/packages/backend/src/core/entities/NoteEntityService.ts +++ b/packages/backend/src/core/entities/NoteEntityService.ts @@ -17,6 +17,7 @@ import { DebounceLoader } from '@/misc/loader.js'; import { IdService } from '@/core/IdService.js'; import { shouldHideNoteByTime } from '@/misc/should-hide-note-by-time.js'; import { ReactionsBufferingService } from '@/core/ReactionsBufferingService.js'; +import { CacheService } from '@/core/CacheService.js'; import type { OnModuleInit } from '@nestjs/common'; import type { CustomEmojiService } from '../CustomEmojiService.js'; import type { ReactionService } from '../ReactionService.js'; @@ -66,6 +67,7 @@ export class NoteEntityService implements OnModuleInit { private reactionService: ReactionService; private reactionsBufferingService: ReactionsBufferingService; private idService: IdService; + private cacheService: CacheService; private noteLoader = new DebounceLoader(this.findNoteOrFail); constructor( @@ -101,6 +103,7 @@ export class NoteEntityService implements OnModuleInit { //private reactionService: ReactionService, //private reactionsBufferingService: ReactionsBufferingService, //private idService: IdService, + //private cacheService: CacheService, ) { } @@ -111,6 +114,7 @@ export class NoteEntityService implements OnModuleInit { this.reactionService = this.moduleRef.get('ReactionService'); this.reactionsBufferingService = this.moduleRef.get('ReactionsBufferingService'); this.idService = this.moduleRef.get('IdService'); + this.cacheService = this.moduleRef.get('CacheService'); } @bindThis @@ -125,75 +129,65 @@ export class NoteEntityService implements OnModuleInit { } @bindThis - private async hideNote(packedNote: Packed<'Note'>, meId: MiUser['id'] | null): Promise { - if (meId === packedNote.userId) return; - + public async shouldHideNote(packedNote: Packed<'Note'>, meId: MiUser['id'] | null): Promise { + if (meId === packedNote.userId) return false; // TODO: isVisibleForMe を使うようにしても良さそう(型違うけど) - let hide = false; if (packedNote.user.requireSigninToViewContents && meId == null) { - hide = true; + return true; } - if (!hide) { - const hiddenBefore = packedNote.user.makeNotesHiddenBefore; - if (shouldHideNoteByTime(hiddenBefore, packedNote.createdAt)) { - hide = true; - } + const hiddenBefore = packedNote.user.makeNotesHiddenBefore; + if (shouldHideNoteByTime(hiddenBefore, packedNote.createdAt)) { + return true; } // visibility が specified かつ自分が指定されていなかったら非表示 - if (!hide) { - if (packedNote.visibility === 'specified') { - if (meId == null) { - hide = true; - } else { - // 指定されているかどうか - const specified = packedNote.visibleUserIds!.some(id => meId === id); + if (packedNote.visibility === 'specified') { + if (meId == null) { + return true; + } else { + // 指定されているかどうか + const specified = packedNote.visibleUserIds!.some(id => meId === id); - if (!specified) { - hide = true; - } + if (!specified) { + return true; } } } // visibility が followers かつ自分が投稿者のフォロワーでなかったら非表示 - if (!hide) { - if (packedNote.visibility === 'followers') { - if (meId == null) { - hide = true; - } else if (packedNote.reply && (meId === packedNote.reply.userId)) { - // 自分の投稿に対するリプライ - hide = false; - } else if (packedNote.mentions && packedNote.mentions.some(id => meId === id)) { - // 自分へのメンション - hide = false; - } else { - // フォロワーかどうか - // TODO: 当関数呼び出しごとにクエリが走るのは重そうだからなんとかする - const isFollowing = await this.followingsRepository.exists({ - where: { - followeeId: packedNote.userId, - followerId: meId, - }, - }); - - hide = !isFollowing; + if (packedNote.visibility === 'followers') { + if (meId == null) { + return true; + } else if (packedNote.reply && (meId === packedNote.reply.userId)) { + // 自分の投稿に対するリプライ + return false; + } else if (packedNote.mentions && packedNote.mentions.some(id => meId === id)) { + // 自分へのメンション + return false; + } else { + // フォロワーかどうか + const followings = await this.cacheService.userFollowingsCache.fetch(meId); + if (!Object.hasOwn(followings, packedNote.userId)) { + return true; } } } - if (hide) { - packedNote.visibleUserIds = undefined; - packedNote.fileIds = []; - packedNote.files = []; - packedNote.text = null; - packedNote.poll = undefined; - packedNote.cw = null; - packedNote.isHidden = true; - // TODO: hiddenReason みたいなのを提供しても良さそう - } + return false; + } + + @bindThis + public hideNote(packedNote: Packed<'Note'>): void { + packedNote.visibleUserIds = undefined; + packedNote.fileIds = []; + packedNote.files = []; + packedNote.text = null; + packedNote.poll = undefined; + packedNote.cw = null; + packedNote.isHidden = true; + // TODO: hiddenReason みたいなのを提供しても良さそう } @bindThis @@ -278,7 +272,7 @@ export class NoteEntityService implements OnModuleInit { @bindThis public async isVisibleForMe(note: MiNote, meId: MiUser['id'] | null): Promise { - // This code must always be synchronized with the checks in generateVisibilityQuery. + // This code must always be synchronized with the checks in QueryService.generateVisibilityQuery. // visibility が specified かつ自分が指定されていなかったら非表示 if (note.visibility === 'specified') { if (meId == null) { @@ -468,8 +462,8 @@ export class NoteEntityService implements OnModuleInit { this.treatVisibility(packed); - if (!opts.skipHide) { - await this.hideNote(packed, meId); + if (!opts.skipHide && await this.shouldHideNote(packed, meId)) { + this.hideNote(packed); } return packed; diff --git a/packages/backend/src/core/entities/NoteReactionEntityService.ts b/packages/backend/src/core/entities/NoteReactionEntityService.ts index 54ce4d472a..fe4926bfe3 100644 --- a/packages/backend/src/core/entities/NoteReactionEntityService.ts +++ b/packages/backend/src/core/entities/NoteReactionEntityService.ts @@ -54,7 +54,7 @@ export class NoteReactionEntityService implements OnModuleInit { packedUser?: Packed<'UserLite'> }, ): Promise> { - const opts = Object.assign({ + const _opts = Object.assign({ }, options); const reaction = typeof src === 'object' ? src : await this.noteReactionsRepository.findOneByOrFail({ id: src }); @@ -90,7 +90,7 @@ export class NoteReactionEntityService implements OnModuleInit { packedUser?: Packed<'UserLite'> }, ): Promise> { - const opts = Object.assign({ + const _opts = Object.assign({ }, options); const reaction = typeof src === 'object' ? src : await this.noteReactionsRepository.findOneByOrFail({ id: src }); diff --git a/packages/backend/src/core/entities/ReversiGameEntityService.ts b/packages/backend/src/core/entities/ReversiGameEntityService.ts index df042e75c1..21099bad3e 100644 --- a/packages/backend/src/core/entities/ReversiGameEntityService.ts +++ b/packages/backend/src/core/entities/ReversiGameEntityService.ts @@ -14,6 +14,10 @@ import { bindThis } from '@/decorators.js'; import { IdService } from '@/core/IdService.js'; import { UserEntityService } from './UserEntityService.js'; +function assertBw(bw: string): bw is Packed<'ReversiGameDetailed'>['bw'] { + return ['random', '1', '2'].includes(bw); +} + @Injectable() export class ReversiGameEntityService { constructor( @@ -58,7 +62,7 @@ export class ReversiGameEntityService { surrenderedUserId: game.surrenderedUserId, timeoutUserId: game.timeoutUserId, black: game.black, - bw: game.bw, + bw: assertBw(game.bw) ? game.bw : 'random', isLlotheo: game.isLlotheo, canPutEverywhere: game.canPutEverywhere, loopedBoard: game.loopedBoard, @@ -116,7 +120,7 @@ export class ReversiGameEntityService { surrenderedUserId: game.surrenderedUserId, timeoutUserId: game.timeoutUserId, black: game.black, - bw: game.bw, + bw: assertBw(game.bw) ? game.bw : 'random', isLlotheo: game.isLlotheo, canPutEverywhere: game.canPutEverywhere, loopedBoard: game.loopedBoard, diff --git a/packages/backend/src/core/entities/UserEntityService.ts b/packages/backend/src/core/entities/UserEntityService.ts index ac5b855096..0f4051e7b8 100644 --- a/packages/backend/src/core/entities/UserEntityService.ts +++ b/packages/backend/src/core/entities/UserEntityService.ts @@ -720,7 +720,7 @@ export class UserEntityService implements OnModuleInit { me, { ...options, - userProfile: profilesMap.get(u.id), + userProfile: profilesMap?.get(u.id), userRelations: userRelations, userMemos: userMemos, pinNotes: pinNotes, diff --git a/packages/backend/src/daemons/ServerStatsService.ts b/packages/backend/src/daemons/ServerStatsService.ts index d229efb123..a972e5861c 100644 --- a/packages/backend/src/daemons/ServerStatsService.ts +++ b/packages/backend/src/daemons/ServerStatsService.ts @@ -4,13 +4,12 @@ */ import { Inject, Injectable } from '@nestjs/common'; -import si from 'systeminformation'; import Xev from 'xev'; import * as osUtils from 'os-utils'; import { bindThis } from '@/decorators.js'; -import type { OnApplicationShutdown } from '@nestjs/common'; import { MiMeta } from '@/models/_.js'; import { DI } from '@/di-symbols.js'; +import type { OnApplicationShutdown } from '@nestjs/common'; const ev = new Xev(); @@ -97,12 +96,14 @@ function cpuUsage(): Promise { // MEMORY STAT async function mem() { + const si = await import('systeminformation'); const data = await si.mem(); return data; } // NETWORK STAT async function net() { + const si = await import('systeminformation'); const iface = await si.networkInterfaceDefault(); const data = await si.networkStats(iface); return data[0]; @@ -110,5 +111,6 @@ async function net() { // FS STAT async function fs() { + const si = await import('systeminformation'); return await si.disksIO().catch(() => ({ rIO_sec: 0, wIO_sec: 0 })); } diff --git a/packages/backend/src/misc/check-word-mute.ts b/packages/backend/src/misc/check-word-mute.ts index c50f2b723c..0d1c7ee46e 100644 --- a/packages/backend/src/misc/check-word-mute.ts +++ b/packages/backend/src/misc/check-word-mute.ts @@ -56,7 +56,7 @@ export async function checkWordMute(note: NoteLike, me: UserLike | null | undefi try { return new RE2(regexp[1], regexp[2]).test(text); - } catch (err) { + } catch (_) { // This should never happen due to input sanitisation. return false; } diff --git a/packages/backend/src/misc/get-ip-hash.ts b/packages/backend/src/misc/get-ip-hash.ts index e132fa8f31..571996973b 100644 --- a/packages/backend/src/misc/get-ip-hash.ts +++ b/packages/backend/src/misc/get-ip-hash.ts @@ -12,7 +12,7 @@ export function getIpHash(ip: string): string { // (this means for IPv4 the entire address is used) const prefix = IPCIDR.createAddress(ip).mask(64); return 'ip-' + BigInt('0b' + prefix).toString(36); - } catch (e) { + } catch (_) { const prefix = IPCIDR.createAddress(ip.replace(/:[0-9]+$/, '')).mask(64); return 'ip-' + BigInt('0b' + prefix).toString(36); } diff --git a/packages/backend/src/misc/i18n.ts b/packages/backend/src/misc/i18n.ts index 6cbbdef74c..40067cacf5 100644 --- a/packages/backend/src/misc/i18n.ts +++ b/packages/backend/src/misc/i18n.ts @@ -26,7 +26,7 @@ export class I18n> { } } return str; - } catch (e) { + } catch (_) { console.warn(`missing localization '${key}'`); return key; } diff --git a/packages/backend/src/misc/json-schema.ts b/packages/backend/src/misc/json-schema.ts index ed7d5bfc3a..cf233defd9 100644 --- a/packages/backend/src/misc/json-schema.ts +++ b/packages/backend/src/misc/json-schema.ts @@ -64,6 +64,7 @@ import { packedMetaDetailedOnlySchema, packedMetaDetailedSchema, packedMetaLiteSchema, + packedMetaClientOptionsSchema, } from '@/models/json-schema/meta.js'; import { packedUserWebhookSchema } from '@/models/json-schema/user-webhook.js'; import { packedSystemWebhookSchema } from '@/models/json-schema/system-webhook.js'; @@ -135,6 +136,7 @@ export const refs = { MetaLite: packedMetaLiteSchema, MetaDetailedOnly: packedMetaDetailedOnlySchema, MetaDetailed: packedMetaDetailedSchema, + MetaClientOptions: packedMetaClientOptionsSchema, UserWebhook: packedUserWebhookSchema, SystemWebhook: packedSystemWebhookSchema, AbuseReportNotificationRecipient: packedAbuseReportNotificationRecipientSchema, @@ -262,8 +264,6 @@ type ObjectSchemaTypeDef

= never : any; -type ObjectSchemaType

= NullOrUndefined>; - export type SchemaTypeDef

= p['type'] extends 'null' ? null : p['type'] extends 'integer' ? number : diff --git a/packages/backend/src/misc/show-machine-info.ts b/packages/backend/src/misc/show-machine-info.ts index 8ddec35f23..b279eb9546 100644 --- a/packages/backend/src/misc/show-machine-info.ts +++ b/packages/backend/src/misc/show-machine-info.ts @@ -4,15 +4,11 @@ */ import * as os from 'node:os'; -import sysUtils from 'systeminformation'; import type Logger from '@/logger.js'; export async function showMachineInfo(parentLogger: Logger) { const logger = parentLogger.createSubLogger('machine'); logger.debug(`Hostname: ${os.hostname()}`); logger.debug(`Platform: ${process.platform} Arch: ${process.arch}`); - const mem = await sysUtils.mem(); - const totalmem = (mem.total / 1024 / 1024 / 1024).toFixed(1); - const availmem = (mem.available / 1024 / 1024 / 1024).toFixed(1); - logger.debug(`CPU: ${os.cpus().length} core MEM: ${totalmem}GB (available: ${availmem}GB)`); + logger.debug(`CPU: ${os.cpus().length} core MEM: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(1)}GB (available: ${(os.freemem() / 1024 / 1024 / 1024).toFixed(1)}GB)`); } diff --git a/packages/backend/src/misc/split-id-and-objects.ts b/packages/backend/src/misc/split-id-and-objects.ts new file mode 100644 index 0000000000..d23bb93695 --- /dev/null +++ b/packages/backend/src/misc/split-id-and-objects.ts @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * idとオブジェクトを分離する + * @param input idまたはオブジェクトの配列 + * @returns idの配列とオブジェクトの配列 + */ +export function splitIdAndObjects(input: (T | string)[]): { ids: string[]; objects: T[] } { + const ids: string[] = []; + const objects : T[] = []; + + for (const item of input) { + if (typeof item === 'string') { + ids.push(item); + } else { + objects.push(item); + } + } + + return { + ids, + objects, + }; +} diff --git a/packages/backend/src/misc/unique-by-key.ts b/packages/backend/src/misc/unique-by-key.ts new file mode 100644 index 0000000000..4308e29d21 --- /dev/null +++ b/packages/backend/src/misc/unique-by-key.ts @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * itemsの中でkey関数が返す値が重複しないようにした配列を返す + * @param items 重複を除去したい配列 + * @param key 重複判定に使うキーを返す関数 + * @returns 重複を除去した配列 + */ +export function uniqueByKey(items: Iterable, key: (item: TItem) => TKey): TItem[] { + const map = new Map(); + for (const item of items) { + const k = key(item); + if (!map.has(k)) { + map.set(k, item); + } + } + return [...map.values()]; +} diff --git a/packages/backend/src/models/AbuseReportNotificationRecipient.ts b/packages/backend/src/models/AbuseReportNotificationRecipient.ts index 17ec6abed5..daed81c174 100644 --- a/packages/backend/src/models/AbuseReportNotificationRecipient.ts +++ b/packages/backend/src/models/AbuseReportNotificationRecipient.ts @@ -67,7 +67,7 @@ export class MiAbuseReportNotificationRecipient { /** * 通知先のユーザ. */ - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn({ name: 'userId', referencedColumnName: 'id', foreignKeyConstraintName: 'FK_abuse_report_notification_recipient_userId1' }) @@ -76,7 +76,7 @@ export class MiAbuseReportNotificationRecipient { /** * 通知先のユーザプロフィール. */ - @ManyToOne(type => MiUserProfile, { + @ManyToOne(() => MiUserProfile, { onDelete: 'CASCADE', }) @JoinColumn({ name: 'userId', referencedColumnName: 'userId', foreignKeyConstraintName: 'FK_abuse_report_notification_recipient_userId2' }) @@ -96,7 +96,7 @@ export class MiAbuseReportNotificationRecipient { /** * 通知先のシステムWebhook. */ - @ManyToOne(type => MiSystemWebhook, { + @ManyToOne(() => MiSystemWebhook, { onDelete: 'CASCADE', }) @JoinColumn({ name: 'systemWebhookId', referencedColumnName: 'id', foreignKeyConstraintName: 'FK_abuse_report_notification_recipient_systemWebhookId' }) diff --git a/packages/backend/src/models/AbuseUserReport.ts b/packages/backend/src/models/AbuseUserReport.ts index d43ebf9342..cd49fcddfe 100644 --- a/packages/backend/src/models/AbuseUserReport.ts +++ b/packages/backend/src/models/AbuseUserReport.ts @@ -18,7 +18,7 @@ export class MiAbuseUserReport { @Column(id()) public targetUserId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -28,7 +28,7 @@ export class MiAbuseUserReport { @Column(id()) public reporterId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -40,7 +40,7 @@ export class MiAbuseUserReport { }) public assigneeId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/AccessToken.ts b/packages/backend/src/models/AccessToken.ts index 6f98c14ec1..a853dcc6cb 100644 --- a/packages/backend/src/models/AccessToken.ts +++ b/packages/backend/src/models/AccessToken.ts @@ -41,7 +41,7 @@ export class MiAccessToken { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -53,7 +53,7 @@ export class MiAccessToken { }) public appId: MiApp['id'] | null; - @ManyToOne(type => MiApp, { + @ManyToOne(() => MiApp, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Announcement.ts b/packages/backend/src/models/Announcement.ts index d0c59fff50..f664c75262 100644 --- a/packages/backend/src/models/Announcement.ts +++ b/packages/backend/src/models/Announcement.ts @@ -79,7 +79,7 @@ export class MiAnnouncement { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/AnnouncementRead.ts b/packages/backend/src/models/AnnouncementRead.ts index 47de8dd180..2133cff140 100644 --- a/packages/backend/src/models/AnnouncementRead.ts +++ b/packages/backend/src/models/AnnouncementRead.ts @@ -18,7 +18,7 @@ export class MiAnnouncementRead { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -28,7 +28,7 @@ export class MiAnnouncementRead { @Column(id()) public announcementId: MiAnnouncement['id']; - @ManyToOne(type => MiAnnouncement, { + @ManyToOne(() => MiAnnouncement, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Antenna.ts b/packages/backend/src/models/Antenna.ts index ccc8823703..3433cf20af 100644 --- a/packages/backend/src/models/Antenna.ts +++ b/packages/backend/src/models/Antenna.ts @@ -24,7 +24,7 @@ export class MiAntenna { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -45,7 +45,7 @@ export class MiAntenna { }) public userListId: MiUserList['id'] | null; - @ManyToOne(type => MiUserList, { + @ManyToOne(() => MiUserList, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/App.ts b/packages/backend/src/models/App.ts index 0185e2995c..bbb80b99ef 100644 --- a/packages/backend/src/models/App.ts +++ b/packages/backend/src/models/App.ts @@ -20,7 +20,7 @@ export class MiApp { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'SET NULL', nullable: true, }) diff --git a/packages/backend/src/models/AuthSession.ts b/packages/backend/src/models/AuthSession.ts index 03050ba955..a7273e63bf 100644 --- a/packages/backend/src/models/AuthSession.ts +++ b/packages/backend/src/models/AuthSession.ts @@ -25,7 +25,7 @@ export class MiAuthSession { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', nullable: true, }) @@ -35,7 +35,7 @@ export class MiAuthSession { @Column(id()) public appId: MiApp['id']; - @ManyToOne(type => MiApp, { + @ManyToOne(() => MiApp, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Blocking.ts b/packages/backend/src/models/Blocking.ts index 34a6efe5a6..49b584f509 100644 --- a/packages/backend/src/models/Blocking.ts +++ b/packages/backend/src/models/Blocking.ts @@ -20,7 +20,7 @@ export class MiBlocking { }) public blockeeId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -33,7 +33,7 @@ export class MiBlocking { }) public blockerId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/BubbleGameRecord.ts b/packages/backend/src/models/BubbleGameRecord.ts index 686e39c118..5dd7009fc6 100644 --- a/packages/backend/src/models/BubbleGameRecord.ts +++ b/packages/backend/src/models/BubbleGameRecord.ts @@ -18,7 +18,7 @@ export class MiBubbleGameRecord { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Channel.ts b/packages/backend/src/models/Channel.ts index f5e9b17e3e..5a5b914eb1 100644 --- a/packages/backend/src/models/Channel.ts +++ b/packages/backend/src/models/Channel.ts @@ -27,7 +27,7 @@ export class MiChannel { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'SET NULL', }) @JoinColumn() @@ -52,7 +52,7 @@ export class MiChannel { }) public bannerId: MiDriveFile['id'] | null; - @ManyToOne(type => MiDriveFile, { + @ManyToOne(() => MiDriveFile, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/ChannelFavorite.ts b/packages/backend/src/models/ChannelFavorite.ts index 167f41cf16..4f49468598 100644 --- a/packages/backend/src/models/ChannelFavorite.ts +++ b/packages/backend/src/models/ChannelFavorite.ts @@ -20,7 +20,7 @@ export class MiChannelFavorite { }) public channelId: MiChannel['id']; - @ManyToOne(type => MiChannel, { + @ManyToOne(() => MiChannel, { onDelete: 'CASCADE', }) @JoinColumn() @@ -32,7 +32,7 @@ export class MiChannelFavorite { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChannelFollowing.ts b/packages/backend/src/models/ChannelFollowing.ts index c7afdd05b0..7597e704a8 100644 --- a/packages/backend/src/models/ChannelFollowing.ts +++ b/packages/backend/src/models/ChannelFollowing.ts @@ -21,7 +21,7 @@ export class MiChannelFollowing { }) public followeeId: MiChannel['id']; - @ManyToOne(type => MiChannel, { + @ManyToOne(() => MiChannel, { onDelete: 'CASCADE', }) @JoinColumn() @@ -34,7 +34,7 @@ export class MiChannelFollowing { }) public followerId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChannelMuting.ts b/packages/backend/src/models/ChannelMuting.ts index 11ac7e5cef..b7054c9c5f 100644 --- a/packages/backend/src/models/ChannelMuting.ts +++ b/packages/backend/src/models/ChannelMuting.ts @@ -20,7 +20,7 @@ export class MiChannelMuting { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -32,7 +32,7 @@ export class MiChannelMuting { }) public channelId: MiChannel['id']; - @ManyToOne(type => MiChannel, { + @ManyToOne(() => MiChannel, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChatApproval.ts b/packages/backend/src/models/ChatApproval.ts index 55c9f07e9a..bd2509b67f 100644 --- a/packages/backend/src/models/ChatApproval.ts +++ b/packages/backend/src/models/ChatApproval.ts @@ -19,7 +19,7 @@ export class MiChatApproval { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -31,7 +31,7 @@ export class MiChatApproval { }) public otherId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChatMessage.ts b/packages/backend/src/models/ChatMessage.ts index 3d2b64268e..530ef9b842 100644 --- a/packages/backend/src/models/ChatMessage.ts +++ b/packages/backend/src/models/ChatMessage.ts @@ -20,7 +20,7 @@ export class MiChatMessage { }) public fromUserId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -32,7 +32,7 @@ export class MiChatMessage { }) public toUserId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -44,7 +44,7 @@ export class MiChatMessage { }) public toRoomId: MiChatRoom['id'] | null; - @ManyToOne(type => MiChatRoom, { + @ManyToOne(() => MiChatRoom, { onDelete: 'CASCADE', }) @JoinColumn() @@ -72,7 +72,7 @@ export class MiChatMessage { }) public fileId: MiDriveFile['id'] | null; - @ManyToOne(type => MiDriveFile, { + @ManyToOne(() => MiDriveFile, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/ChatRoom.ts b/packages/backend/src/models/ChatRoom.ts index ad2a910b78..c148b16af8 100644 --- a/packages/backend/src/models/ChatRoom.ts +++ b/packages/backend/src/models/ChatRoom.ts @@ -23,7 +23,7 @@ export class MiChatRoom { }) public ownerId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChatRoomInvitation.ts b/packages/backend/src/models/ChatRoomInvitation.ts index 36ce12bc92..5827d0401d 100644 --- a/packages/backend/src/models/ChatRoomInvitation.ts +++ b/packages/backend/src/models/ChatRoomInvitation.ts @@ -20,7 +20,7 @@ export class MiChatRoomInvitation { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -32,7 +32,7 @@ export class MiChatRoomInvitation { }) public roomId: MiChatRoom['id']; - @ManyToOne(type => MiChatRoom, { + @ManyToOne(() => MiChatRoom, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ChatRoomMembership.ts b/packages/backend/src/models/ChatRoomMembership.ts index 3cb5524859..d59b4426df 100644 --- a/packages/backend/src/models/ChatRoomMembership.ts +++ b/packages/backend/src/models/ChatRoomMembership.ts @@ -20,7 +20,7 @@ export class MiChatRoomMembership { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -32,7 +32,7 @@ export class MiChatRoomMembership { }) public roomId: MiChatRoom['id']; - @ManyToOne(type => MiChatRoom, { + @ManyToOne(() => MiChatRoom, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Clip.ts b/packages/backend/src/models/Clip.ts index 6295a329fb..ddd0298f44 100644 --- a/packages/backend/src/models/Clip.ts +++ b/packages/backend/src/models/Clip.ts @@ -25,7 +25,7 @@ export class MiClip { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ClipFavorite.ts b/packages/backend/src/models/ClipFavorite.ts index 40bdb9f4aa..2d46fd0f0e 100644 --- a/packages/backend/src/models/ClipFavorite.ts +++ b/packages/backend/src/models/ClipFavorite.ts @@ -18,7 +18,7 @@ export class MiClipFavorite { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiClipFavorite { @Column(id()) public clipId: MiClip['id']; - @ManyToOne(type => MiClip, { + @ManyToOne(() => MiClip, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ClipNote.ts b/packages/backend/src/models/ClipNote.ts index 6e1d2bec4c..23df66c4e0 100644 --- a/packages/backend/src/models/ClipNote.ts +++ b/packages/backend/src/models/ClipNote.ts @@ -21,7 +21,7 @@ export class MiClipNote { }) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() @@ -34,7 +34,7 @@ export class MiClipNote { }) public clipId: MiClip['id']; - @ManyToOne(type => MiClip, { + @ManyToOne(() => MiClip, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/DriveFile.ts b/packages/backend/src/models/DriveFile.ts index 7b03e3e494..79189b10eb 100644 --- a/packages/backend/src/models/DriveFile.ts +++ b/packages/backend/src/models/DriveFile.ts @@ -22,7 +22,7 @@ export class MiDriveFile { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'SET NULL', }) @JoinColumn() @@ -142,7 +142,7 @@ export class MiDriveFile { }) public folderId: MiDriveFolder['id'] | null; - @ManyToOne(type => MiDriveFolder, { + @ManyToOne(() => MiDriveFolder, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/DriveFolder.ts b/packages/backend/src/models/DriveFolder.ts index 07046d6e11..7e34c07f46 100644 --- a/packages/backend/src/models/DriveFolder.ts +++ b/packages/backend/src/models/DriveFolder.ts @@ -26,7 +26,7 @@ export class MiDriveFolder { }) public userId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -40,7 +40,7 @@ export class MiDriveFolder { }) public parentId: MiDriveFolder['id'] | null; - @ManyToOne(type => MiDriveFolder, { + @ManyToOne(() => MiDriveFolder, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/Flash.ts b/packages/backend/src/models/Flash.ts index 5db7dca992..ed677a9de3 100644 --- a/packages/backend/src/models/Flash.ts +++ b/packages/backend/src/models/Flash.ts @@ -38,7 +38,7 @@ export class MiFlash { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/FlashLike.ts b/packages/backend/src/models/FlashLike.ts index a9fb48123e..0d99c2a9ae 100644 --- a/packages/backend/src/models/FlashLike.ts +++ b/packages/backend/src/models/FlashLike.ts @@ -18,7 +18,7 @@ export class MiFlashLike { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiFlashLike { @Column(id()) public flashId: MiFlash['id']; - @ManyToOne(type => MiFlash, { + @ManyToOne(() => MiFlash, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/FollowRequest.ts b/packages/backend/src/models/FollowRequest.ts index 3ff5e7a478..468829b7e8 100644 --- a/packages/backend/src/models/FollowRequest.ts +++ b/packages/backend/src/models/FollowRequest.ts @@ -20,7 +20,7 @@ export class MiFollowRequest { }) public followeeId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -33,7 +33,7 @@ export class MiFollowRequest { }) public followerId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Following.ts b/packages/backend/src/models/Following.ts index 62cbc29f26..fe62166287 100644 --- a/packages/backend/src/models/Following.ts +++ b/packages/backend/src/models/Following.ts @@ -21,7 +21,7 @@ export class MiFollowing { }) public followeeId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -34,7 +34,7 @@ export class MiFollowing { }) public followerId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/GalleryLike.ts b/packages/backend/src/models/GalleryLike.ts index ed0963122d..787b38e46d 100644 --- a/packages/backend/src/models/GalleryLike.ts +++ b/packages/backend/src/models/GalleryLike.ts @@ -18,7 +18,7 @@ export class MiGalleryLike { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiGalleryLike { @Column(id()) public postId: MiGalleryPost['id']; - @ManyToOne(type => MiGalleryPost, { + @ManyToOne(() => MiGalleryPost, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/GalleryPost.ts b/packages/backend/src/models/GalleryPost.ts index 04d8823e37..f66956628b 100644 --- a/packages/backend/src/models/GalleryPost.ts +++ b/packages/backend/src/models/GalleryPost.ts @@ -36,7 +36,7 @@ export class MiGalleryPost { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Meta.ts b/packages/backend/src/models/Meta.ts index 205c9eeb89..620853450c 100644 --- a/packages/backend/src/models/Meta.ts +++ b/packages/backend/src/models/Meta.ts @@ -21,7 +21,7 @@ export class MiMeta { }) public rootUserId: MiUser['id'] | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'SET NULL', nullable: true, }) @@ -725,7 +725,11 @@ export class MiMeta { @Column('jsonb', { default: { }, }) - public clientOptions: Record; + public clientOptions: { + entrancePageStyle: 'classic' | 'simple'; + showTimelineForVisitor: boolean; + showActivitiesForVisitor: boolean; + }; } export type SoftwareSuspension = { diff --git a/packages/backend/src/models/ModerationLog.ts b/packages/backend/src/models/ModerationLog.ts index edde315fdf..c22114a36d 100644 --- a/packages/backend/src/models/ModerationLog.ts +++ b/packages/backend/src/models/ModerationLog.ts @@ -16,7 +16,7 @@ export class MiModerationLog { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Muting.ts b/packages/backend/src/models/Muting.ts index 07ab9bfcd1..982fc1e9e4 100644 --- a/packages/backend/src/models/Muting.ts +++ b/packages/backend/src/models/Muting.ts @@ -32,7 +32,7 @@ export class MiMuting { }) public muteeId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -45,7 +45,7 @@ export class MiMuting { }) public muterId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Note.ts b/packages/backend/src/models/Note.ts index 23e5960b60..089fe8f188 100644 --- a/packages/backend/src/models/Note.ts +++ b/packages/backend/src/models/Note.ts @@ -35,7 +35,7 @@ export class MiNote { }) public replyId: MiNote['id'] | null; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { createForeignKeyConstraints: false, }) @JoinColumn() @@ -49,7 +49,7 @@ export class MiNote { }) public renoteId: MiNote['id'] | null; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { createForeignKeyConstraints: false, }) @JoinColumn() @@ -83,7 +83,7 @@ export class MiNote { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -208,7 +208,7 @@ export class MiNote { }) public channelId: MiChannel['id'] | null; - @ManyToOne(type => MiChannel, { + @ManyToOne(() => MiChannel, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/NoteDraft.ts b/packages/backend/src/models/NoteDraft.ts index f078e8c21b..5bfd9699fe 100644 --- a/packages/backend/src/models/NoteDraft.ts +++ b/packages/backend/src/models/NoteDraft.ts @@ -27,7 +27,7 @@ export class MiNoteDraft { public replyId: MiNote['id'] | null; // There is a possibility that replyId is not null but reply is null when the reply note is deleted. - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { createForeignKeyConstraints: false, }) @JoinColumn() @@ -42,7 +42,7 @@ export class MiNoteDraft { public renoteId: MiNote['id'] | null; // There is a possibility that renoteId is not null but renote is null when the renote note is deleted. - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { createForeignKeyConstraints: false, }) @JoinColumn() @@ -66,7 +66,7 @@ export class MiNoteDraft { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -120,7 +120,7 @@ export class MiNoteDraft { // There is a possibility that channelId is not null but channel is null when the channel is deleted. // (deleting channel is not implemented so it's not happening now but may happen in the future) - @ManyToOne(type => MiChannel, { + @ManyToOne(() => MiChannel, { createForeignKeyConstraints: false, }) @JoinColumn() diff --git a/packages/backend/src/models/NoteFavorite.ts b/packages/backend/src/models/NoteFavorite.ts index cf76c767b0..0e498eb70d 100644 --- a/packages/backend/src/models/NoteFavorite.ts +++ b/packages/backend/src/models/NoteFavorite.ts @@ -18,7 +18,7 @@ export class MiNoteFavorite { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiNoteFavorite { @Column(id()) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/NoteReaction.ts b/packages/backend/src/models/NoteReaction.ts index 42dfcaa9ad..98263081ab 100644 --- a/packages/backend/src/models/NoteReaction.ts +++ b/packages/backend/src/models/NoteReaction.ts @@ -18,7 +18,7 @@ export class MiNoteReaction { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -28,7 +28,7 @@ export class MiNoteReaction { @Column(id()) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/NoteThreadMuting.ts b/packages/backend/src/models/NoteThreadMuting.ts index e7bd39f348..32bb829c0b 100644 --- a/packages/backend/src/models/NoteThreadMuting.ts +++ b/packages/backend/src/models/NoteThreadMuting.ts @@ -19,7 +19,7 @@ export class MiNoteThreadMuting { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Page.ts b/packages/backend/src/models/Page.ts index d46f6e9d16..8811200801 100644 --- a/packages/backend/src/models/Page.ts +++ b/packages/backend/src/models/Page.ts @@ -56,7 +56,7 @@ export class MiPage { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -68,7 +68,7 @@ export class MiPage { }) public eyeCatchingImageId: MiDriveFile['id'] | null; - @ManyToOne(type => MiDriveFile, { + @ManyToOne(() => MiDriveFile, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/PageLike.ts b/packages/backend/src/models/PageLike.ts index 05ca22cf2c..cf3025ae1c 100644 --- a/packages/backend/src/models/PageLike.ts +++ b/packages/backend/src/models/PageLike.ts @@ -18,7 +18,7 @@ export class MiPageLike { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiPageLike { @Column(id()) public pageId: MiPage['id']; - @ManyToOne(type => MiPage, { + @ManyToOne(() => MiPage, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/PasswordResetRequest.ts b/packages/backend/src/models/PasswordResetRequest.ts index fdaf21056b..3379b540ee 100644 --- a/packages/backend/src/models/PasswordResetRequest.ts +++ b/packages/backend/src/models/PasswordResetRequest.ts @@ -24,7 +24,7 @@ export class MiPasswordResetRequest { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Poll.ts b/packages/backend/src/models/Poll.ts index ca985c8b24..d82e29fb85 100644 --- a/packages/backend/src/models/Poll.ts +++ b/packages/backend/src/models/Poll.ts @@ -15,7 +15,7 @@ export class MiPoll { @PrimaryColumn(id()) public noteId: MiNote['id']; - @OneToOne(type => MiNote, { + @OneToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/PollVote.ts b/packages/backend/src/models/PollVote.ts index b5c780293c..600ca8ea41 100644 --- a/packages/backend/src/models/PollVote.ts +++ b/packages/backend/src/models/PollVote.ts @@ -18,7 +18,7 @@ export class MiPollVote { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -28,7 +28,7 @@ export class MiPollVote { @Column(id()) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/PromoNote.ts b/packages/backend/src/models/PromoNote.ts index ae27adec9e..871f7471fc 100644 --- a/packages/backend/src/models/PromoNote.ts +++ b/packages/backend/src/models/PromoNote.ts @@ -13,7 +13,7 @@ export class MiPromoNote { @PrimaryColumn(id()) public noteId: MiNote['id']; - @OneToOne(type => MiNote, { + @OneToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/PromoRead.ts b/packages/backend/src/models/PromoRead.ts index b2a698cc7b..15a3573ef3 100644 --- a/packages/backend/src/models/PromoRead.ts +++ b/packages/backend/src/models/PromoRead.ts @@ -18,7 +18,7 @@ export class MiPromoRead { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiPromoRead { @Column(id()) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/RegistrationTicket.ts b/packages/backend/src/models/RegistrationTicket.ts index 0a4e4b9189..07216599d3 100644 --- a/packages/backend/src/models/RegistrationTicket.ts +++ b/packages/backend/src/models/RegistrationTicket.ts @@ -23,7 +23,7 @@ export class MiRegistrationTicket { }) public expiresAt: Date | null; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -36,7 +36,7 @@ export class MiRegistrationTicket { }) public createdById: MiUser['id'] | null; - @OneToOne(type => MiUser, { + @OneToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/RegistryItem.ts b/packages/backend/src/models/RegistryItem.ts index 335e8b9eab..869980bbff 100644 --- a/packages/backend/src/models/RegistryItem.ts +++ b/packages/backend/src/models/RegistryItem.ts @@ -25,7 +25,7 @@ export class MiRegistryItem { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/RenoteMuting.ts b/packages/backend/src/models/RenoteMuting.ts index 448a0b7663..b760a09c53 100644 --- a/packages/backend/src/models/RenoteMuting.ts +++ b/packages/backend/src/models/RenoteMuting.ts @@ -20,7 +20,7 @@ export class MiRenoteMuting { }) public muteeId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -33,7 +33,7 @@ export class MiRenoteMuting { }) public muterId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/ReversiGame.ts b/packages/backend/src/models/ReversiGame.ts index 6b29a0ce8c..fbbf24792f 100644 --- a/packages/backend/src/models/ReversiGame.ts +++ b/packages/backend/src/models/ReversiGame.ts @@ -27,7 +27,7 @@ export class MiReversiGame { @Column(id()) public user1Id: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -36,7 +36,7 @@ export class MiReversiGame { @Column(id()) public user2Id: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/RoleAssignment.ts b/packages/backend/src/models/RoleAssignment.ts index 37755d631b..cb96377f66 100644 --- a/packages/backend/src/models/RoleAssignment.ts +++ b/packages/backend/src/models/RoleAssignment.ts @@ -21,7 +21,7 @@ export class MiRoleAssignment { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -34,7 +34,7 @@ export class MiRoleAssignment { }) public roleId: MiRole['id']; - @ManyToOne(type => MiRole, { + @ManyToOne(() => MiRole, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Signin.ts b/packages/backend/src/models/Signin.ts index f8ff9c57d7..59cbad735d 100644 --- a/packages/backend/src/models/Signin.ts +++ b/packages/backend/src/models/Signin.ts @@ -16,7 +16,7 @@ export class MiSignin { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/SwSubscription.ts b/packages/backend/src/models/SwSubscription.ts index 0c531132b3..a95aede44f 100644 --- a/packages/backend/src/models/SwSubscription.ts +++ b/packages/backend/src/models/SwSubscription.ts @@ -16,7 +16,7 @@ export class MiSwSubscription { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/SystemAccount.ts b/packages/backend/src/models/SystemAccount.ts index f32880b81d..2a48e62ed1 100644 --- a/packages/backend/src/models/SystemAccount.ts +++ b/packages/backend/src/models/SystemAccount.ts @@ -18,7 +18,7 @@ export class MiSystemAccount { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/User.ts b/packages/backend/src/models/User.ts index a6e9edcf5f..084dd35485 100644 --- a/packages/backend/src/models/User.ts +++ b/packages/backend/src/models/User.ts @@ -99,7 +99,7 @@ export class MiUser { }) public avatarId: MiDriveFile['id'] | null; - @OneToOne(type => MiDriveFile, { + @OneToOne(() => MiDriveFile, { onDelete: 'SET NULL', }) @JoinColumn() @@ -112,7 +112,7 @@ export class MiUser { }) public bannerId: MiDriveFile['id'] | null; - @OneToOne(type => MiDriveFile, { + @OneToOne(() => MiDriveFile, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/UserKeypair.ts b/packages/backend/src/models/UserKeypair.ts index f5252d126c..894739c84c 100644 --- a/packages/backend/src/models/UserKeypair.ts +++ b/packages/backend/src/models/UserKeypair.ts @@ -12,7 +12,7 @@ export class MiUserKeypair { @PrimaryColumn(id()) public userId: MiUser['id']; - @OneToOne(type => MiUser, { + @OneToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserList.ts b/packages/backend/src/models/UserList.ts index 5fb991a87d..05fd833b6f 100644 --- a/packages/backend/src/models/UserList.ts +++ b/packages/backend/src/models/UserList.ts @@ -25,7 +25,7 @@ export class MiUserList { }) public isPublic: boolean; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserListFavorite.ts b/packages/backend/src/models/UserListFavorite.ts index 80b2d61eb7..67ab92d98c 100644 --- a/packages/backend/src/models/UserListFavorite.ts +++ b/packages/backend/src/models/UserListFavorite.ts @@ -18,7 +18,7 @@ export class MiUserListFavorite { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiUserListFavorite { @Column(id()) public userListId: MiUserList['id']; - @ManyToOne(type => MiUserList, { + @ManyToOne(() => MiUserList, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserListMembership.ts b/packages/backend/src/models/UserListMembership.ts index af659d071d..1a2b3fffc1 100644 --- a/packages/backend/src/models/UserListMembership.ts +++ b/packages/backend/src/models/UserListMembership.ts @@ -21,7 +21,7 @@ export class MiUserListMembership { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -34,7 +34,7 @@ export class MiUserListMembership { }) public userListId: MiUserList['id']; - @ManyToOne(type => MiUserList, { + @ManyToOne(() => MiUserList, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserMemo.ts b/packages/backend/src/models/UserMemo.ts index 29e28d290a..facc8c6b1c 100644 --- a/packages/backend/src/models/UserMemo.ts +++ b/packages/backend/src/models/UserMemo.ts @@ -20,7 +20,7 @@ export class MiUserMemo { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -33,7 +33,7 @@ export class MiUserMemo { }) public targetUserId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserNotePining.ts b/packages/backend/src/models/UserNotePining.ts index 92c5cd55d0..950da2ad22 100644 --- a/packages/backend/src/models/UserNotePining.ts +++ b/packages/backend/src/models/UserNotePining.ts @@ -18,7 +18,7 @@ export class MiUserNotePining { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -27,7 +27,7 @@ export class MiUserNotePining { @Column(id()) public noteId: MiNote['id']; - @ManyToOne(type => MiNote, { + @ManyToOne(() => MiNote, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserProfile.ts b/packages/backend/src/models/UserProfile.ts index 501b539210..b05bf14ef9 100644 --- a/packages/backend/src/models/UserProfile.ts +++ b/packages/backend/src/models/UserProfile.ts @@ -17,7 +17,7 @@ export class MiUserProfile { @PrimaryColumn(id()) public userId: MiUser['id']; - @OneToOne(type => MiUser, { + @OneToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() @@ -215,7 +215,7 @@ export class MiUserProfile { }) public pinnedPageId: MiPage['id'] | null; - @OneToOne(type => MiPage, { + @OneToOne(() => MiPage, { onDelete: 'SET NULL', }) @JoinColumn() diff --git a/packages/backend/src/models/UserPublickey.ts b/packages/backend/src/models/UserPublickey.ts index 6bcd785304..8c23d368e9 100644 --- a/packages/backend/src/models/UserPublickey.ts +++ b/packages/backend/src/models/UserPublickey.ts @@ -12,7 +12,7 @@ export class MiUserPublickey { @PrimaryColumn(id()) public userId: MiUser['id']; - @OneToOne(type => MiUser, { + @OneToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/UserSecurityKey.ts b/packages/backend/src/models/UserSecurityKey.ts index 0babbe1abe..577ec359e4 100644 --- a/packages/backend/src/models/UserSecurityKey.ts +++ b/packages/backend/src/models/UserSecurityKey.ts @@ -18,7 +18,7 @@ export class MiUserSecurityKey { @Column(id()) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/Webhook.ts b/packages/backend/src/models/Webhook.ts index b4cab4edc8..5f833115cc 100644 --- a/packages/backend/src/models/Webhook.ts +++ b/packages/backend/src/models/Webhook.ts @@ -22,7 +22,7 @@ export class MiWebhook { }) public userId: MiUser['id']; - @ManyToOne(type => MiUser, { + @ManyToOne(() => MiUser, { onDelete: 'CASCADE', }) @JoinColumn() diff --git a/packages/backend/src/models/json-schema/meta.ts b/packages/backend/src/models/json-schema/meta.ts index a0e7d490b3..0c3ec141bc 100644 --- a/packages/backend/src/models/json-schema/meta.ts +++ b/packages/backend/src/models/json-schema/meta.ts @@ -72,8 +72,7 @@ export const packedMetaLiteSchema = { optional: false, nullable: true, }, clientOptions: { - type: 'object', - optional: false, nullable: false, + ref: 'MetaClientOptions', }, disableRegistration: { type: 'boolean', @@ -397,3 +396,23 @@ export const packedMetaDetailedSchema = { }, ], } as const; + +export const packedMetaClientOptionsSchema = { + type: 'object', + optional: false, nullable: false, + properties: { + entrancePageStyle: { + type: 'string', + enum: ['classic', 'simple'], + optional: false, nullable: false, + }, + showTimelineForVisitor: { + type: 'boolean', + optional: false, nullable: false, + }, + showActivitiesForVisitor: { + type: 'boolean', + optional: false, nullable: false, + }, + }, +} as const; diff --git a/packages/backend/src/models/json-schema/reversi-game.ts b/packages/backend/src/models/json-schema/reversi-game.ts index cb37200384..378ae41cb5 100644 --- a/packages/backend/src/models/json-schema/reversi-game.ts +++ b/packages/backend/src/models/json-schema/reversi-game.ts @@ -81,6 +81,7 @@ export const packedReversiGameLiteSchema = { bw: { type: 'string', optional: false, nullable: false, + enum: ['random', '1', '2'], }, noIrregularRules: { type: 'boolean', @@ -199,6 +200,7 @@ export const packedReversiGameDetailedSchema = { bw: { type: 'string', optional: false, nullable: false, + enum: ['random', '1', '2'], }, noIrregularRules: { type: 'boolean', diff --git a/packages/backend/src/models/json-schema/user.ts b/packages/backend/src/models/json-schema/user.ts index b5fd38a7d7..f71ec1d023 100644 --- a/packages/backend/src/models/json-schema/user.ts +++ b/packages/backend/src/models/json-schema/user.ts @@ -618,6 +618,9 @@ export const packedMeDetailedOnlySchema = { achievementEarned: { optional: true, ...notificationRecieveConfig }, app: { optional: true, ...notificationRecieveConfig }, test: { optional: true, ...notificationRecieveConfig }, + login: { optional: true, ...notificationRecieveConfig }, + createToken: { optional: true, ...notificationRecieveConfig }, + exportCompleted: { optional: true, ...notificationRecieveConfig }, }, }, emailNotificationTypes: { diff --git a/packages/backend/src/queue/processors/ExportCustomEmojisProcessorService.ts b/packages/backend/src/queue/processors/ExportCustomEmojisProcessorService.ts index e237cd4975..53ecd2d180 100644 --- a/packages/backend/src/queue/processors/ExportCustomEmojisProcessorService.ts +++ b/packages/backend/src/queue/processors/ExportCustomEmojisProcessorService.ts @@ -123,8 +123,8 @@ export class ExportCustomEmojisProcessorService { metaStream.end(); // Create archive - await new Promise(async (resolve) => { - const [archivePath, archiveCleanup] = await createTemp(); + const [archivePath, archiveCleanup] = await createTemp(); + await new Promise((resolve) => { const archiveStream = fs.createWriteStream(archivePath); const archive = archiver('zip', { zlib: { level: 0 }, diff --git a/packages/backend/src/queue/processors/PostScheduledNoteProcessorService.ts b/packages/backend/src/queue/processors/PostScheduledNoteProcessorService.ts index d0eaeee090..719a09980c 100644 --- a/packages/backend/src/queue/processors/PostScheduledNoteProcessorService.ts +++ b/packages/backend/src/queue/processors/PostScheduledNoteProcessorService.ts @@ -63,7 +63,7 @@ export class PostScheduledNoteProcessorService { this.notificationService.createNotification(draft.userId, 'scheduledNotePosted', { noteId: note.id, }); - } catch (err) { + } catch (_) { this.notificationService.createNotification(draft.userId, 'scheduledNotePostFailed', { noteDraftId: draft.id, }); diff --git a/packages/backend/src/server/ActivityPubServerService.ts b/packages/backend/src/server/ActivityPubServerService.ts index a5fb5b82e3..5d9ce78793 100644 --- a/packages/backend/src/server/ActivityPubServerService.ts +++ b/packages/backend/src/server/ActivityPubServerService.ts @@ -30,9 +30,9 @@ import { bindThis } from '@/decorators.js'; import { IActivity } from '@/core/activitypub/type.js'; import { isQuote, isRenote } from '@/misc/is-renote.js'; import * as Acct from '@/misc/acct.js'; +import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js'; import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions, FastifyBodyParser } from 'fastify'; import type { FindOptionsWhere } from 'typeorm'; -import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js'; const ACTIVITY_JSON = 'application/activity+json; charset=utf-8'; const LD_JSON = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"; charset=utf-8'; @@ -116,7 +116,7 @@ export class ActivityPubServerService { try { signature = httpSignature.parseRequest(request.raw, { 'headers': ['(request-target)', 'host', 'date'], authorizationHeaderName: 'signature' }); - } catch (e) { + } catch (_) { reply.code(401); return; } @@ -131,6 +131,7 @@ export class ActivityPubServerService { if (signature.params.headers.indexOf('digest') === -1) { // Digest not found. reply.code(401); + return; } else { const digest = request.headers.digest; diff --git a/packages/backend/src/server/FileServerService.ts b/packages/backend/src/server/FileServerService.ts index 772c37094c..f5034d0733 100644 --- a/packages/backend/src/server/FileServerService.ts +++ b/packages/backend/src/server/FileServerService.ts @@ -7,27 +7,22 @@ import * as fs from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; import { Inject, Injectable } from '@nestjs/common'; -import rename from 'rename'; -import sharp from 'sharp'; -import { sharpBmp } from '@misskey-dev/sharp-read-bmp'; import type { Config } from '@/config.js'; -import type { MiDriveFile, DriveFilesRepository } from '@/models/_.js'; +import type { DriveFilesRepository } from '@/models/_.js'; import { DI } from '@/di-symbols.js'; -import { createTemp } from '@/misc/create-temp.js'; -import { FILE_TYPE_BROWSERSAFE } from '@/const.js'; import { StatusError } from '@/misc/status-error.js'; import type Logger from '@/logger.js'; import { DownloadService } from '@/core/DownloadService.js'; -import { IImageStreamable, ImageProcessingService, webpDefault } from '@/core/ImageProcessingService.js'; -import { VideoProcessingService } from '@/core/VideoProcessingService.js'; import { InternalStorageService } from '@/core/InternalStorageService.js'; -import { contentDisposition } from '@/misc/content-disposition.js'; import { FileInfoService } from '@/core/FileInfoService.js'; +import { ImageProcessingService } from '@/core/ImageProcessingService.js'; +import { VideoProcessingService } from '@/core/VideoProcessingService.js'; import { LoggerService } from '@/core/LoggerService.js'; import { bindThis } from '@/decorators.js'; -import { isMimeImage } from '@/misc/is-mime-image.js'; -import { correctFilename } from '@/misc/correct-filename.js'; import { handleRequestRedirectToOmitSearch } from '@/misc/fastify-hook-handlers.js'; +import { FileServerDriveHandler } from './file/FileServerDriveHandler.js'; +import { FileServerFileResolver } from './file/FileServerFileResolver.js'; +import { FileServerProxyHandler } from './file/FileServerProxyHandler.js'; import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions } from 'fastify'; const _filename = fileURLToPath(import.meta.url); @@ -38,6 +33,9 @@ const assets = `${_dirname}/../../server/file/assets/`; @Injectable() export class FileServerService { private logger: Logger; + private driveHandler: FileServerDriveHandler; + private proxyHandler: FileServerProxyHandler; + private fileResolver: FileServerFileResolver; constructor( @Inject(DI.config) @@ -54,6 +52,24 @@ export class FileServerService { private loggerService: LoggerService, ) { this.logger = this.loggerService.getLogger('server', 'gray'); + this.fileResolver = new FileServerFileResolver( + this.driveFilesRepository, + this.fileInfoService, + this.downloadService, + this.internalStorageService, + ); + this.driveHandler = new FileServerDriveHandler( + this.config, + this.fileResolver, + assets, + this.videoProcessingService, + ); + this.proxyHandler = new FileServerProxyHandler( + this.config, + this.fileResolver, + assets, + this.imageProcessingService, + ); //this.createServer = this.createServer.bind(this); } @@ -78,7 +94,7 @@ export class FileServerService { }); fastify.get<{ Params: { key: string; } }>('/files/:key', async (request, reply) => { - return await this.sendDriveFile(request, reply) + return await this.driveHandler.handle(request, reply) .catch(err => this.errorHandler(request, reply, err)); }); fastify.get<{ Params: { key: string; } }>('/files/:key/*', async (request, reply) => { @@ -91,7 +107,7 @@ export class FileServerService { Params: { url: string; }; Querystring: { url?: string; }; }>('/proxy/:url*', async (request, reply) => { - return await this.proxyHandler(request, reply) + return await this.proxyHandler.handle(request, reply) .catch(err => this.errorHandler(request, reply, err)); }); @@ -116,462 +132,4 @@ export class FileServerService { reply.code(500); return; } - - @bindThis - private async sendDriveFile(request: FastifyRequest<{ Params: { key: string; } }>, reply: FastifyReply) { - const key = request.params.key; - const file = await this.getFileFromKey(key).then(); - - if (file === '404') { - reply.code(404); - reply.header('Cache-Control', 'max-age=86400'); - return reply.sendFile('/dummy.png', assets); - } - - if (file === '204') { - reply.code(204); - reply.header('Cache-Control', 'max-age=86400'); - return; - } - - try { - if (file.state === 'remote') { - let image: IImageStreamable | null = null; - - if (file.fileRole === 'thumbnail') { - if (isMimeImage(file.mime, 'sharp-convertible-image-with-bmp')) { - reply.header('Cache-Control', 'max-age=31536000, immutable'); - - const url = new URL(`${this.config.mediaProxy}/static.webp`); - url.searchParams.set('url', file.url); - url.searchParams.set('static', '1'); - - file.cleanup(); - return await reply.redirect(url.toString(), 301); - } else if (file.mime.startsWith('video/')) { - const externalThumbnail = this.videoProcessingService.getExternalVideoThumbnailUrl(file.url); - if (externalThumbnail) { - file.cleanup(); - return await reply.redirect(externalThumbnail, 301); - } - - image = await this.videoProcessingService.generateVideoThumbnail(file.path); - } - } - - if (file.fileRole === 'webpublic') { - if (['image/svg+xml'].includes(file.mime)) { - reply.header('Cache-Control', 'max-age=31536000, immutable'); - - const url = new URL(`${this.config.mediaProxy}/svg.webp`); - url.searchParams.set('url', file.url); - - file.cleanup(); - return await reply.redirect(url.toString(), 301); - } - } - - if (!image) { - if (request.headers.range && file.file.size > 0) { - const range = request.headers.range as string; - const parts = range.replace(/bytes=/, '').split('-'); - const start = parseInt(parts[0], 10); - let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1; - if (end > file.file.size) { - end = file.file.size - 1; - } - const chunksize = end - start + 1; - - image = { - data: fs.createReadStream(file.path, { - start, - end, - }), - ext: file.ext, - type: file.mime, - }; - - reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); - reply.header('Accept-Ranges', 'bytes'); - reply.header('Content-Length', chunksize); - reply.code(206); - } else { - image = { - data: fs.createReadStream(file.path), - ext: file.ext, - type: file.mime, - }; - } - } - - if ('pipe' in image.data && typeof image.data.pipe === 'function') { - // image.dataがstreamなら、stream終了後にcleanup - image.data.on('end', file.cleanup); - image.data.on('close', file.cleanup); - } else { - // image.dataがstreamでないなら直ちにcleanup - file.cleanup(); - } - - 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', - correctFilename(file.filename, image.ext), - ), - ); - return image.data; - } - - if (file.fileRole !== 'original') { - const filename = rename(file.filename, { - suffix: file.fileRole === 'thumbnail' ? '-thumb' : '-web', - extname: file.ext ? `.${file.ext}` : '.unknown', - }).toString(); - - reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.mime) ? file.mime : 'application/octet-stream'); - reply.header('Cache-Control', 'max-age=31536000, immutable'); - reply.header('Content-Disposition', contentDisposition('inline', filename)); - - if (request.headers.range && file.file.size > 0) { - const range = request.headers.range as string; - const parts = range.replace(/bytes=/, '').split('-'); - const start = parseInt(parts[0], 10); - let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1; - if (end > file.file.size) { - end = file.file.size - 1; - } - const chunksize = end - start + 1; - const fileStream = fs.createReadStream(file.path, { - start, - end, - }); - reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); - reply.header('Accept-Ranges', 'bytes'); - reply.header('Content-Length', chunksize); - reply.code(206); - return fileStream; - } - - 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)); - - if (request.headers.range && file.file.size > 0) { - const range = request.headers.range as string; - const parts = range.replace(/bytes=/, '').split('-'); - const start = parseInt(parts[0], 10); - let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1; - if (end > file.file.size) { - end = file.file.size - 1; - } - const chunksize = end - start + 1; - const fileStream = fs.createReadStream(file.path, { - start, - end, - }); - reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); - reply.header('Accept-Ranges', 'bytes'); - reply.header('Content-Length', chunksize); - reply.code(206); - return fileStream; - } - - return fs.createReadStream(file.path); - } - } catch (e) { - if ('cleanup' in file) file.cleanup(); - throw e; - } - } - - @bindThis - private async proxyHandler(request: FastifyRequest<{ Params: { url: string; }; Querystring: { url?: string; }; }>, reply: FastifyReply) { - const url = 'url' in request.query ? request.query.url : 'https://' + request.params.url; - - if (typeof url !== 'string') { - reply.code(400); - return; - } - - // アバタークロップなど、どうしてもオリジンである必要がある場合 - const mustOrigin = 'origin' in request.query; - - if (this.config.externalMediaProxyEnabled && !mustOrigin) { - // 外部のメディアプロキシが有効なら、そちらにリダイレクト - - reply.header('Cache-Control', 'public, max-age=259200'); // 3 days - - const url = new URL(`${this.config.mediaProxy}/${request.params.url || ''}`); - - for (const [key, value] of Object.entries(request.query)) { - url.searchParams.append(key, value); - } - - return await reply.redirect( - url.toString(), - 301, - ); - } - - if (!request.headers['user-agent']) { - throw new StatusError('User-Agent is required', 400, 'User-Agent is required'); - } else if (request.headers['user-agent'].toLowerCase().indexOf('misskey/') !== -1) { - throw new StatusError('Refusing to proxy a request from another proxy', 403, 'Proxy is recursive'); - } - - // Create temp file - const file = await this.getStreamAndTypeFromUrl(url); - if (file === '404') { - reply.code(404); - reply.header('Cache-Control', 'max-age=86400'); - return reply.sendFile('/dummy.png', assets); - } - - if (file === '204') { - reply.code(204); - reply.header('Cache-Control', 'max-age=86400'); - return; - } - - try { - const isConvertibleImage = isMimeImage(file.mime, 'sharp-convertible-image-with-bmp'); - const isAnimationConvertibleImage = isMimeImage(file.mime, 'sharp-animation-convertible-image-with-bmp'); - - if ( - 'emoji' in request.query || - 'avatar' in request.query || - 'static' in request.query || - 'preview' in request.query || - 'badge' in request.query - ) { - if (!isConvertibleImage) { - // 画像でないなら404でお茶を濁す - throw new StatusError('Unexpected mime', 404); - } - } - - let image: IImageStreamable | null = null; - if ('emoji' in request.query || 'avatar' in request.query) { - if (!isAnimationConvertibleImage && !('static' in request.query)) { - image = { - data: fs.createReadStream(file.path), - ext: file.ext, - type: file.mime, - }; - } else { - const data = (await sharpBmp(file.path, file.mime, { animated: !('static' in request.query) })) - .resize({ - height: 'emoji' in request.query ? 128 : 320, - withoutEnlargement: true, - }) - .webp(webpDefault); - - image = { - data, - ext: 'webp', - type: 'image/webp', - }; - } - } else if ('static' in request.query) { - image = this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 498, 422); - } else if ('preview' in request.query) { - image = this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 200, 200); - } else if ('badge' in request.query) { - const mask = (await sharpBmp(file.path, file.mime)) - .resize(96, 96, { - fit: 'contain', - position: 'centre', - withoutEnlargement: false, - }) - .greyscale() - .normalise() - .linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast - .flatten({ background: '#000' }) - .toColorspace('b-w'); - - const stats = await mask.clone().stats(); - - if (stats.entropy < 0.1) { - // エントロピーがあまりない場合は404にする - throw new StatusError('Skip to provide badge', 404); - } - - const data = sharp({ - create: { width: 96, height: 96, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } }, - }) - .pipelineColorspace('b-w') - .boolean(await mask.png().toBuffer(), 'eor'); - - image = { - data: await data.png().toBuffer(), - ext: 'png', - type: 'image/png', - }; - } else if (file.mime === 'image/svg+xml') { - image = this.imageProcessingService.convertToWebpStream(file.path, 2048, 2048); - } else if (!file.mime.startsWith('image/') || !FILE_TYPE_BROWSERSAFE.includes(file.mime)) { - throw new StatusError('Rejected type', 403, 'Rejected type'); - } - - if (!image) { - if (request.headers.range && file.file && file.file.size > 0) { - const range = request.headers.range as string; - const parts = range.replace(/bytes=/, '').split('-'); - const start = parseInt(parts[0], 10); - let end = parts[1] ? parseInt(parts[1], 10) : file.file.size - 1; - if (end > file.file.size) { - end = file.file.size - 1; - } - const chunksize = end - start + 1; - - image = { - data: fs.createReadStream(file.path, { - start, - end, - }), - ext: file.ext, - type: file.mime, - }; - - reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); - reply.header('Accept-Ranges', 'bytes'); - reply.header('Content-Length', chunksize); - reply.code(206); - } else { - image = { - data: fs.createReadStream(file.path), - ext: file.ext, - type: file.mime, - }; - } - } - - if ('cleanup' in file) { - if ('pipe' in image.data && typeof image.data.pipe === 'function') { - // image.dataがstreamなら、stream終了後にcleanup - image.data.on('end', file.cleanup); - image.data.on('close', file.cleanup); - } else { - // image.dataがstreamでないなら直ちにcleanup - file.cleanup(); - } - } - - reply.header('Content-Type', image.type); - reply.header('Cache-Control', 'max-age=31536000, immutable'); - reply.header('Content-Disposition', - contentDisposition( - 'inline', - correctFilename(file.filename, image.ext), - ), - ); - return image.data; - } catch (e) { - if ('cleanup' in file) file.cleanup(); - throw e; - } - } - - @bindThis - private async getStreamAndTypeFromUrl(url: string): Promise< - { state: 'remote'; fileRole?: 'thumbnail' | 'webpublic' | 'original'; file?: MiDriveFile; mime: string; ext: string | null; path: string; cleanup: () => void; filename: string; } - | { state: 'stored_internal'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; mime: string; ext: string | null; path: string; } - | '404' - | '204' - > { - if (url.startsWith(`${this.config.url}/files/`)) { - const key = url.replace(`${this.config.url}/files/`, '').split('/').shift(); - if (!key) throw new StatusError('Invalid File Key', 400, 'Invalid File Key'); - - return await this.getFileFromKey(key); - } - - return await this.downloadAndDetectTypeFromUrl(url); - } - - @bindThis - private async downloadAndDetectTypeFromUrl(url: string): Promise< - { state: 'remote'; mime: string; ext: string | null; path: string; cleanup: () => void; filename: string; } - > { - const [path, cleanup] = await createTemp(); - try { - const { filename } = await this.downloadService.downloadUrl(url, path); - - const { mime, ext } = await this.fileInfoService.detectType(path); - - return { - state: 'remote', - mime, ext, - path, cleanup, - filename, - }; - } catch (e) { - cleanup(); - throw e; - } - } - - @bindThis - private async getFileFromKey(key: string): Promise< - { state: 'remote'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; url: string; mime: string; ext: string | null; path: string; cleanup: () => void; } - | { state: 'stored_internal'; fileRole: 'thumbnail' | 'webpublic' | 'original'; file: MiDriveFile; filename: string; mime: string; ext: string | null; path: string; } - | '404' - | '204' - > { - // Fetch drive file - const file = await this.driveFilesRepository.createQueryBuilder('file') - .where('file.accessKey = :accessKey', { accessKey: key }) - .orWhere('file.thumbnailAccessKey = :thumbnailAccessKey', { thumbnailAccessKey: key }) - .orWhere('file.webpublicAccessKey = :webpublicAccessKey', { webpublicAccessKey: key }) - .getOne(); - - if (file == null) return '404'; - - const isThumbnail = file.thumbnailAccessKey === key; - const isWebpublic = file.webpublicAccessKey === key; - - if (!file.storedInternal) { - if (!(file.isLink && file.uri)) return '204'; - const result = await this.downloadAndDetectTypeFromUrl(file.uri); - file.size = (await fs.promises.stat(result.path)).size; // DB file.sizeは正確とは限らないので - return { - ...result, - url: file.uri, - fileRole: isThumbnail ? 'thumbnail' : isWebpublic ? 'webpublic' : 'original', - file, - filename: file.name, - }; - } - - const path = this.internalStorageService.resolvePath(key); - - if (isThumbnail || isWebpublic) { - const { mime, ext } = await this.fileInfoService.detectType(path); - return { - state: 'stored_internal', - fileRole: isThumbnail ? 'thumbnail' : 'webpublic', - file, - filename: file.name, - mime, ext, - path, - }; - } - - return { - state: 'stored_internal', - fileRole: 'original', - file, - filename: file.name, - // 古いファイルは修正前のmimeを持っているのでできるだけ修正してあげる - mime: this.fileInfoService.fixMime(file.type), - ext: null, - path, - }; - } } diff --git a/packages/backend/src/server/NodeinfoServerService.ts b/packages/backend/src/server/NodeinfoServerService.ts index 239ef82dec..93c36f5365 100644 --- a/packages/backend/src/server/NodeinfoServerService.ts +++ b/packages/backend/src/server/NodeinfoServerService.ts @@ -48,8 +48,6 @@ export class NodeinfoServerService { @bindThis public createServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) { const nodeinfo2 = async (version: number) => { - const now = Date.now(); - const notesChart = await this.notesChart.getChart('hour', 1, null); const localPosts = notesChart.local.total[0]; diff --git a/packages/backend/src/server/ServerModule.ts b/packages/backend/src/server/ServerModule.ts index 111421472d..e228d51103 100644 --- a/packages/backend/src/server/ServerModule.ts +++ b/packages/backend/src/server/ServerModule.ts @@ -13,7 +13,6 @@ import { NodeinfoServerService } from './NodeinfoServerService.js'; import { ServerService } from './ServerService.js'; import { WellKnownServerService } from './WellKnownServerService.js'; import { GetterService } from './api/GetterService.js'; -import { ChannelsService } from './api/stream/ChannelsService.js'; import { ActivityPubServerService } from './ActivityPubServerService.js'; import { ApiLoggerService } from './api/ApiLoggerService.js'; import { ApiServerService } from './api/ApiServerService.js'; @@ -31,24 +30,26 @@ import { UrlPreviewService } from './web/UrlPreviewService.js'; import { ClientLoggerService } from './web/ClientLoggerService.js'; import { OAuth2ProviderService } from './oauth/OAuth2ProviderService.js'; -import { MainChannelService } from './api/stream/channels/main.js'; -import { AdminChannelService } from './api/stream/channels/admin.js'; -import { AntennaChannelService } from './api/stream/channels/antenna.js'; -import { ChannelChannelService } from './api/stream/channels/channel.js'; -import { DriveChannelService } from './api/stream/channels/drive.js'; -import { GlobalTimelineChannelService } from './api/stream/channels/global-timeline.js'; -import { HashtagChannelService } from './api/stream/channels/hashtag.js'; -import { HomeTimelineChannelService } from './api/stream/channels/home-timeline.js'; -import { HybridTimelineChannelService } from './api/stream/channels/hybrid-timeline.js'; -import { LocalTimelineChannelService } from './api/stream/channels/local-timeline.js'; -import { QueueStatsChannelService } from './api/stream/channels/queue-stats.js'; -import { ServerStatsChannelService } from './api/stream/channels/server-stats.js'; -import { UserListChannelService } from './api/stream/channels/user-list.js'; -import { RoleTimelineChannelService } from './api/stream/channels/role-timeline.js'; -import { ChatUserChannelService } from './api/stream/channels/chat-user.js'; -import { ChatRoomChannelService } from './api/stream/channels/chat-room.js'; -import { ReversiChannelService } from './api/stream/channels/reversi.js'; -import { ReversiGameChannelService } from './api/stream/channels/reversi-game.js'; +import MainStreamConnection from '@/server/api/stream/Connection.js'; +import { MainChannel } from './api/stream/channels/main.js'; +import { AdminChannel } from './api/stream/channels/admin.js'; +import { AntennaChannel } from './api/stream/channels/antenna.js'; +import { ChannelChannel } from './api/stream/channels/channel.js'; +import { DriveChannel } from './api/stream/channels/drive.js'; +import { GlobalTimelineChannel } from './api/stream/channels/global-timeline.js'; +import { HashtagChannel } from './api/stream/channels/hashtag.js'; +import { HomeTimelineChannel } from './api/stream/channels/home-timeline.js'; +import { HybridTimelineChannel } from './api/stream/channels/hybrid-timeline.js'; +import { LocalTimelineChannel } from './api/stream/channels/local-timeline.js'; +import { QueueStatsChannel } from './api/stream/channels/queue-stats.js'; +import { ServerStatsChannel } from './api/stream/channels/server-stats.js'; +import { UserListChannel } from './api/stream/channels/user-list.js'; +import { RoleTimelineChannel } from './api/stream/channels/role-timeline.js'; +import { ChatUserChannel } from './api/stream/channels/chat-user.js'; +import { ChatRoomChannel } from './api/stream/channels/chat-room.js'; +import { ReversiChannel } from './api/stream/channels/reversi.js'; +import { ReversiGameChannel } from './api/stream/channels/reversi-game.js'; +import { NoteStreamingHidingService } from './api/stream/NoteStreamingHidingService.js'; import { SigninWithPasskeyApiService } from './api/SigninWithPasskeyApiService.js'; @Module({ @@ -69,7 +70,7 @@ import { SigninWithPasskeyApiService } from './api/SigninWithPasskeyApiService.j ServerService, WellKnownServerService, GetterService, - ChannelsService, + MainStreamConnection, ApiCallService, ApiLoggerService, ApiServerService, @@ -80,24 +81,25 @@ import { SigninWithPasskeyApiService } from './api/SigninWithPasskeyApiService.j SigninService, SignupApiService, StreamingApiServerService, - MainChannelService, - AdminChannelService, - AntennaChannelService, - ChannelChannelService, - DriveChannelService, - GlobalTimelineChannelService, - HashtagChannelService, - RoleTimelineChannelService, - ChatUserChannelService, - ChatRoomChannelService, - ReversiChannelService, - ReversiGameChannelService, - HomeTimelineChannelService, - HybridTimelineChannelService, - LocalTimelineChannelService, - QueueStatsChannelService, - ServerStatsChannelService, - UserListChannelService, + MainChannel, + AdminChannel, + AntennaChannel, + ChannelChannel, + DriveChannel, + GlobalTimelineChannel, + HashtagChannel, + RoleTimelineChannel, + ChatUserChannel, + ChatRoomChannel, + ReversiChannel, + ReversiGameChannel, + HomeTimelineChannel, + HybridTimelineChannel, + LocalTimelineChannel, + QueueStatsChannel, + ServerStatsChannel, + UserListChannel, + NoteStreamingHidingService, OpenApiServerService, OAuth2ProviderService, ], diff --git a/packages/backend/src/server/ServerService.ts b/packages/backend/src/server/ServerService.ts index 1286b4dad6..ef9ac81f95 100644 --- a/packages/backend/src/server/ServerService.ts +++ b/packages/backend/src/server/ServerService.ts @@ -75,7 +75,7 @@ export class ServerService implements OnApplicationShutdown { @bindThis public async launch(): Promise { const fastify = Fastify({ - trustProxy: this.config.trustProxy ?? true, + trustProxy: this.config.trustProxy, logger: false, }); this.#fastify = fastify; diff --git a/packages/backend/src/server/api/ApiCallService.ts b/packages/backend/src/server/api/ApiCallService.ts index 261e147040..0ccb3df631 100644 --- a/packages/backend/src/server/api/ApiCallService.ts +++ b/packages/backend/src/server/api/ApiCallService.ts @@ -313,16 +313,15 @@ export class ApiCallService implements OnApplicationShutdown { } if (ep.meta.limit) { - let limitActor: string | null; + let limitActor: string | null = null; if (user) { limitActor = user.id; - } else { - if (request.ip === '::1' || request.ip === '127.0.0.1') { - console.warn('request ip is localhost, maybe caused by misconfiguration of trustProxy or reverse proxy'); - limitActor = null; - } else { - limitActor = getIpHash(request.ip); + } else if (this.config.enableIpRateLimit) { + if (process.env.NODE_ENV === 'production' && (request.ip === '::1' || request.ip === '127.0.0.1')) { + this.logger.warn('Recieved API request from localhost IP address for rate limiting in production environment. This is likely due to an improper trustProxy setting in the config file.'); } + + limitActor = getIpHash(request.ip); } const limit = Object.assign({}, ep.meta.limit); @@ -427,7 +426,7 @@ export class ApiCallService implements OnApplicationShutdown { if (['boolean', 'number', 'integer'].includes(param.type ?? '') && typeof data[k] === 'string') { try { data[k] = JSON.parse(data[k]); - } catch (e) { + } catch (_) { throw new ApiError({ message: 'Invalid param.', code: 'INVALID_PARAM', diff --git a/packages/backend/src/server/api/SigninApiService.ts b/packages/backend/src/server/api/SigninApiService.ts index 14726f8411..5c9d16a95a 100644 --- a/packages/backend/src/server/api/SigninApiService.ts +++ b/packages/backend/src/server/api/SigninApiService.ts @@ -15,6 +15,7 @@ import type { UserSecurityKeysRepository, UsersRepository, } from '@/models/_.js'; +import type Logger from '@/logger.js'; import type { Config } from '@/config.js'; import { getIpHash } from '@/misc/get-ip-hash.js'; import type { MiLocalUser } from '@/models/User.js'; @@ -23,6 +24,7 @@ import { bindThis } from '@/decorators.js'; import { WebAuthnService } from '@/core/WebAuthnService.js'; import { UserAuthService } from '@/core/UserAuthService.js'; import { CaptchaService } from '@/core/CaptchaService.js'; +import { LoggerService } from '@/core/LoggerService.js'; import { FastifyReplyError } from '@/misc/fastify-reply-error.js'; import { RateLimiterService } from './RateLimiterService.js'; import { SigninService } from './SigninService.js'; @@ -31,6 +33,8 @@ import type { FastifyReply, FastifyRequest } from 'fastify'; @Injectable() export class SigninApiService { + private logger: Logger; + constructor( @Inject(DI.config) private config: Config, @@ -50,6 +54,7 @@ export class SigninApiService { @Inject(DI.signinsRepository) private signinsRepository: SigninsRepository, + private loggerService: LoggerService, private idService: IdService, private rateLimiterService: RateLimiterService, private signinService: SigninService, @@ -57,6 +62,7 @@ export class SigninApiService { private webAuthnService: WebAuthnService, private captchaService: CaptchaService, ) { + this.logger = this.loggerService.getLogger('Signin'); } @bindThis @@ -89,10 +95,11 @@ export class SigninApiService { return { error }; } - if (request.ip === '::1' || request.ip === '127.0.0.1') { - console.warn('request ip is localhost, maybe caused by misconfiguration of trustProxy or reverse proxy'); - } else { // not more than 1 attempt per second and not more than 10 attempts per hour + if (this.config.enableIpRateLimit) { + if (process.env.NODE_ENV === 'production' && (request.ip === '::1' || request.ip === '127.0.0.1')) { + this.logger.warn('Recieved signin request from localhost IP address for rate limiting in production environment. This is likely due to an improper trustProxy setting in the config file.'); + } const rateLimit = await this.rateLimiterService.limit({ key: 'signin', duration: 60 * 60 * 1000, max: 10, minInterval: 1000 }, getIpHash(request.ip)); if (rateLimit != null) { reply.code(429); @@ -224,7 +231,7 @@ export class SigninApiService { try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { return await fail(403, { id: 'cdf1235b-ac71-46d4-a3a6-84ccce48df6f', }); diff --git a/packages/backend/src/server/api/SigninWithPasskeyApiService.ts b/packages/backend/src/server/api/SigninWithPasskeyApiService.ts index 1b89752340..6feb4c3afa 100644 --- a/packages/backend/src/server/api/SigninWithPasskeyApiService.ts +++ b/packages/backend/src/server/api/SigninWithPasskeyApiService.ts @@ -84,14 +84,16 @@ export class SigninWithPasskeyApiService { return error(status ?? 500, failure ?? { id: '4e30e80c-e338-45a0-8c8f-44455efa3b76' }); }; - if (request.ip === '::1' || request.ip === '127.0.0.1') { - console.warn('request ip is localhost, maybe caused by misconfiguration of trustProxy or reverse proxy'); - } else { + if (this.config.enableIpRateLimit) { + if (process.env.NODE_ENV === 'production' && (request.ip === '::1' || request.ip === '127.0.0.1')) { + this.logger.warn('Recieved signin with passkey request from localhost IP address for rate limiting in production environment. This is likely due to an improper trustProxy setting in the config file.'); + } + try { // Not more than 1 API call per 250ms and not more than 100 attempts per 30min // NOTE: 1 Sign-in require 2 API calls await this.rateLimiterService.limit({ key: 'signin-with-passkey', duration: 60 * 30 * 1000, max: 200, minInterval: 250 }, getIpHash(request.ip)); - } catch (err) { + } catch (_) { reply.code(429); return { error: { diff --git a/packages/backend/src/server/api/SignupApiService.ts b/packages/backend/src/server/api/SignupApiService.ts index 53336a087d..b419c51ef1 100644 --- a/packages/backend/src/server/api/SignupApiService.ts +++ b/packages/backend/src/server/api/SignupApiService.ts @@ -255,7 +255,7 @@ export class SignupApiService { throw new FastifyReplyError(400, 'EXPIRED'); } - const { account, secret } = await this.signupService.signup({ + const { account } = await this.signupService.signup({ username: pendingUser.username, passwordHash: pendingUser.password, }); diff --git a/packages/backend/src/server/api/StreamingApiServerService.ts b/packages/backend/src/server/api/StreamingApiServerService.ts index 21f2f0b7e2..8a317bdc4e 100644 --- a/packages/backend/src/server/api/StreamingApiServerService.ts +++ b/packages/backend/src/server/api/StreamingApiServerService.ts @@ -8,18 +8,14 @@ import { Inject, Injectable } from '@nestjs/common'; import * as Redis from 'ioredis'; import * as WebSocket from 'ws'; import { DI } from '@/di-symbols.js'; -import type { UsersRepository, MiAccessToken } from '@/models/_.js'; -import { NotificationService } from '@/core/NotificationService.js'; +import type { MiAccessToken } from '@/models/_.js'; import { bindThis } from '@/decorators.js'; -import { CacheService } from '@/core/CacheService.js'; import { MiLocalUser } from '@/models/User.js'; import { UserService } from '@/core/UserService.js'; -import { ChannelFollowingService } from '@/core/ChannelFollowingService.js'; -import { ChannelMutingService } from '@/core/ChannelMutingService.js'; import { AuthenticateService, AuthenticationError } from './AuthenticateService.js'; -import MainStreamConnection from './stream/Connection.js'; -import { ChannelsService } from './stream/ChannelsService.js'; +import MainStreamConnection, { ConnectionRequest } from './stream/Connection.js'; import type * as http from 'node:http'; +import { ContextIdFactory, ModuleRef } from '@nestjs/core'; @Injectable() export class StreamingApiServerService { @@ -31,16 +27,9 @@ export class StreamingApiServerService { @Inject(DI.redisForSub) private redisForSub: Redis.Redis, - @Inject(DI.usersRepository) - private usersRepository: UsersRepository, - - private cacheService: CacheService, + private moduleRef: ModuleRef, private authenticateService: AuthenticateService, - private channelsService: ChannelsService, - private notificationService: NotificationService, private usersService: UserService, - private channelFollowingService: ChannelFollowingService, - private channelMutingService: ChannelMutingService, ) { } @@ -94,14 +83,12 @@ export class StreamingApiServerService { return; } - const stream = new MainStreamConnection( - this.channelsService, - this.notificationService, - this.cacheService, - this.channelFollowingService, - this.channelMutingService, - user, app, - ); + const contextId = ContextIdFactory.create(); + this.moduleRef.registerRequestByContextId({ + user, + token: app, + }, contextId); + const stream = await this.moduleRef.create(MainStreamConnection, contextId); await stream.init(); @@ -124,7 +111,7 @@ export class StreamingApiServerService { user: MiLocalUser | null; app: MiAccessToken | null }) => { - const { stream, user, app } = ctx; + const { stream, user } = ctx; const ev = new EventEmitter(); diff --git a/packages/backend/src/server/api/endpoint-list.ts b/packages/backend/src/server/api/endpoint-list.ts index 9aecc0f0fd..6679005c3c 100644 --- a/packages/backend/src/server/api/endpoint-list.ts +++ b/packages/backend/src/server/api/endpoint-list.ts @@ -391,6 +391,7 @@ export * as 'users/featured-notes' from './endpoints/users/featured-notes.js'; export * as 'users/flashs' from './endpoints/users/flashs.js'; export * as 'users/followers' from './endpoints/users/followers.js'; export * as 'users/following' from './endpoints/users/following.js'; +export * as 'users/get-following-users-by-birthday' from './endpoints/users/get-following-users-by-birthday.js'; export * as 'users/gallery/posts' from './endpoints/users/gallery/posts.js'; export * as 'users/get-frequently-replied-users' from './endpoints/users/get-frequently-replied-users.js'; export * as 'users/lists/create' from './endpoints/users/lists/create.js'; diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/create.ts b/packages/backend/src/server/api/endpoints/admin/announcements/create.ts index b8bfda73a4..74462b302a 100644 --- a/packages/backend/src/server/api/endpoints/admin/announcements/create.ts +++ b/packages/backend/src/server/api/endpoints/admin/announcements/create.ts @@ -72,7 +72,7 @@ export default class extends Endpoint { // eslint- private announcementService: AnnouncementService, ) { super(meta, paramDef, async (ps, me) => { - const { raw, packed } = await this.announcementService.create({ + const { packed } = await this.announcementService.create({ updatedAt: null, title: ps.title, text: ps.text, diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/list.ts b/packages/backend/src/server/api/endpoints/admin/announcements/list.ts index 804bd5d9b9..aeebceed5a 100644 --- a/packages/backend/src/server/api/endpoints/admin/announcements/list.ts +++ b/packages/backend/src/server/api/endpoints/admin/announcements/list.ts @@ -51,11 +51,13 @@ export const meta = { }, icon: { type: 'string', - optional: false, nullable: true, + optional: false, nullable: false, + enum: ['info', 'warning', 'error', 'success'], }, display: { type: 'string', optional: false, nullable: false, + enum: ['normal', 'banner', 'dialog'], }, isActive: { type: 'boolean', 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 cf03859ce5..d4305e7d7c 100644 --- a/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts +++ b/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts @@ -76,7 +76,7 @@ export default class extends Endpoint { // eslint- try { // Create file driveFile = await this.driveService.uploadFromUrl({ url: emoji.originalUrl, user: null, force: true }); - } catch (e) { + } catch (_) { // TODO: need to return Drive Error throw new ApiError(); } diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts b/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts index 660aa55bf8..b9448b4bc2 100644 --- a/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts +++ b/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts @@ -24,39 +24,7 @@ export const meta = { optional: false, nullable: false, items: { type: 'object', - optional: false, nullable: false, - properties: { - id: { - type: 'string', - optional: false, nullable: false, - format: 'id', - }, - aliases: { - type: 'array', - optional: false, nullable: false, - items: { - type: 'string', - optional: false, nullable: false, - }, - }, - name: { - type: 'string', - optional: false, nullable: false, - }, - category: { - type: 'string', - optional: false, nullable: true, - }, - host: { - type: 'string', - optional: false, nullable: true, - description: 'The local host is represented with `null`.', - }, - url: { - type: 'string', - optional: false, nullable: false, - }, - }, + ref: 'EmojiDetailed', }, }, } as const; diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/list.ts b/packages/backend/src/server/api/endpoints/admin/emoji/list.ts index 34d200455e..658367409c 100644 --- a/packages/backend/src/server/api/endpoints/admin/emoji/list.ts +++ b/packages/backend/src/server/api/endpoints/admin/emoji/list.ts @@ -24,39 +24,7 @@ export const meta = { optional: false, nullable: false, items: { type: 'object', - optional: false, nullable: false, - properties: { - id: { - type: 'string', - optional: false, nullable: false, - format: 'id', - }, - aliases: { - type: 'array', - optional: false, nullable: false, - items: { - type: 'string', - optional: false, nullable: false, - }, - }, - name: { - type: 'string', - optional: false, nullable: false, - }, - category: { - type: 'string', - optional: false, nullable: true, - }, - host: { - type: 'string', - optional: false, nullable: true, - description: 'The local host is represented with `null`. The field exists for compatibility with other API endpoints that return files.', - }, - url: { - type: 'string', - optional: false, nullable: false, - }, - }, + ref: 'EmojiDetailed', }, }, } as const; diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/update.ts b/packages/backend/src/server/api/endpoints/admin/emoji/update.ts index 7bde10af46..e20bc21f6b 100644 --- a/packages/backend/src/server/api/endpoints/admin/emoji/update.ts +++ b/packages/backend/src/server/api/endpoints/admin/emoji/update.ts @@ -117,7 +117,7 @@ export default class extends Endpoint { // eslint- case 'SAME_NAME_EMOJI_EXISTS': throw new ApiError(meta.errors.sameNameEmojiExists); } // 網羅性チェック - const mustBeNever: never = error; + const _mustBeNever: never = error; }); } } diff --git a/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts b/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts index b7781b8c99..bdd0ee6cac 100644 --- a/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts +++ b/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts @@ -13,7 +13,7 @@ export const meta = { tags: ['admin'], requireCredential: true, - requireModerator: true, + requireAdmin: true, kind: 'read:admin:user-ips', res: { type: 'array', diff --git a/packages/backend/src/server/api/endpoints/admin/meta.ts b/packages/backend/src/server/api/endpoints/admin/meta.ts index 2c7f793584..5beed3a7e8 100644 --- a/packages/backend/src/server/api/endpoints/admin/meta.ts +++ b/packages/backend/src/server/api/endpoints/admin/meta.ts @@ -428,8 +428,7 @@ export const meta = { optional: false, nullable: true, }, clientOptions: { - type: 'object', - optional: false, nullable: false, + ref: 'MetaClientOptions', }, description: { type: 'string', diff --git a/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts b/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts index f3e440b4cb..86158d7e22 100644 --- a/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts +++ b/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts @@ -52,18 +52,14 @@ export default class extends Endpoint { // eslint- super(meta, paramDef, async (ps, me) => { const jobs = await this.deliverQueue.getJobs(['delayed']); - const res = [] as [string, number][]; + const counts = new Map(); for (const job of jobs) { const host = new URL(job.data.to).host; - if (res.find(x => x[0] === host)) { - res.find(x => x[0] === host)![1]++; - } else { - res.push([host, 1]); - } + counts.set(host, (counts.get(host) ?? 0) + 1); } - res.sort((a, b) => b[1] - a[1]); + const res = [...counts.entries()].sort((a, b) => b[1] - a[1]); return res; }); diff --git a/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts b/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts index e7589cba81..ad6a823b8f 100644 --- a/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts +++ b/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts @@ -52,18 +52,14 @@ export default class extends Endpoint { // eslint- super(meta, paramDef, async (ps, me) => { const jobs = await this.inboxQueue.getJobs(['delayed']); - const res = [] as [string, number][]; + const counts = new Map(); for (const job of jobs) { const host = new URL(job.data.signature.keyId).host; - if (res.find(x => x[0] === host)) { - res.find(x => x[0] === host)![1]++; - } else { - res.push([host, 1]); - } + counts.set(host, (counts.get(host) ?? 0) + 1); } - res.sort((a, b) => b[1] - a[1]); + const res = [...counts.entries()].sort((a, b) => b[1] - a[1]); return res; }); diff --git a/packages/backend/src/server/api/endpoints/admin/server-info.ts b/packages/backend/src/server/api/endpoints/admin/server-info.ts index 80b6a4d32e..603be514c8 100644 --- a/packages/backend/src/server/api/endpoints/admin/server-info.ts +++ b/packages/backend/src/server/api/endpoints/admin/server-info.ts @@ -4,7 +4,6 @@ */ import * as os from 'node:os'; -import si from 'systeminformation'; import { Inject, Injectable } from '@nestjs/common'; import { DataSource } from 'typeorm'; import * as Redis from 'ioredis'; @@ -112,6 +111,8 @@ export default class extends Endpoint { // eslint- ) { super(meta, paramDef, async () => { + const si = await import('systeminformation'); + const memStats = await si.mem(); const fsStats = await si.fsSize(); const netInterface = await si.networkInterfaceDefault(); 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 b3c2cecc67..372fe3a25f 100644 --- a/packages/backend/src/server/api/endpoints/admin/update-meta.ts +++ b/packages/backend/src/server/api/endpoints/admin/update-meta.ts @@ -3,7 +3,8 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Injectable, Inject } from '@nestjs/common'; +import { DI } from '@/di-symbols.js'; import type { MiMeta } from '@/models/Meta.js'; import { ModerationLogService } from '@/core/ModerationLogService.js'; import { Endpoint } from '@/server/api/endpoint-base.js'; @@ -67,7 +68,14 @@ export const paramDef = { description: { type: 'string', nullable: true }, defaultLightTheme: { type: 'string', nullable: true }, defaultDarkTheme: { type: 'string', nullable: true }, - clientOptions: { type: 'object', nullable: false }, + clientOptions: { + type: 'object', nullable: false, + properties: { + entrancePageStyle: { type: 'string', nullable: false, enum: ['classic', 'simple'] }, + showTimelineForVisitor: { type: 'boolean', nullable: false }, + showActivitiesForVisitor: { type: 'boolean', nullable: false }, + }, + }, cacheRemoteFiles: { type: 'boolean' }, cacheRemoteSensitiveFiles: { type: 'boolean' }, emailRequiredForSignup: { type: 'boolean' }, @@ -217,6 +225,9 @@ export const paramDef = { @Injectable() export default class extends Endpoint { // eslint-disable-line import/no-default-export constructor( + @Inject(DI.meta) + private serverSettings: MiMeta, + private metaService: MetaService, private moderationLogService: ModerationLogService, ) { @@ -329,7 +340,10 @@ export default class extends Endpoint { // eslint- } if (ps.clientOptions !== undefined) { - set.clientOptions = ps.clientOptions; + set.clientOptions = { + ...this.serverSettings.clientOptions, + ...ps.clientOptions, + }; } if (ps.cacheRemoteFiles !== undefined) { diff --git a/packages/backend/src/server/api/endpoints/ap/get.ts b/packages/backend/src/server/api/endpoints/ap/get.ts index 14286bc23e..ff03fce72b 100644 --- a/packages/backend/src/server/api/endpoints/ap/get.ts +++ b/packages/backend/src/server/api/endpoints/ap/get.ts @@ -43,7 +43,7 @@ export default class extends Endpoint { // eslint- private apResolverService: ApResolverService, ) { super(meta, paramDef, async (ps, me) => { - const resolver = this.apResolverService.createResolver(); + const resolver = await this.apResolverService.createResolver(); const object = await resolver.resolve(ps.uri); return object; }); diff --git a/packages/backend/src/server/api/endpoints/ap/show.ts b/packages/backend/src/server/api/endpoints/ap/show.ts index fe48e7497a..47da6b4fbd 100644 --- a/packages/backend/src/server/api/endpoints/ap/show.ts +++ b/packages/backend/src/server/api/endpoints/ap/show.ts @@ -148,7 +148,7 @@ export default class extends Endpoint { // eslint- if (this.utilityService.isSelfHost(host)) return null; // リモートから一旦オブジェクトフェッチ - const resolver = this.apResolverService.createResolver(); + const resolver = await this.apResolverService.createResolver(); // allow ap/show exclusively to lookup URLs that are cross-origin or non-canonical (like https://alice.example.com/@bob@bob.example.com -> https://bob.example.com/@bob) const object = await resolver.resolve(uri, FetchAllowSoftFailMask.CrossOrigin | FetchAllowSoftFailMask.NonCanonicalId).catch((err) => { if (err instanceof IdentifiableError) { @@ -215,7 +215,7 @@ export default class extends Endpoint { // eslint- type: 'Note', object, }; - } catch (e) { + } catch (_) { return null; } } diff --git a/packages/backend/src/server/api/endpoints/channels/timeline.ts b/packages/backend/src/server/api/endpoints/channels/timeline.ts index 4f56bc2110..e088869457 100644 --- a/packages/backend/src/server/api/endpoints/channels/timeline.ts +++ b/packages/backend/src/server/api/endpoints/channels/timeline.ts @@ -15,6 +15,7 @@ import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointServ import { MiLocalUser } from '@/models/User.js'; import { ChannelMutingService } from '@/core/ChannelMutingService.js'; import { ApiError } from '../../error.js'; +import { Brackets } from 'typeorm'; export const meta = { tags: ['notes', 'channels'], @@ -132,7 +133,10 @@ export default class extends Endpoint { // eslint- .then(x => x.map(x => x.id).filter(x => x !== ps.channelId)); if (mutingChannelIds.length > 0) { query.andWhere('note.channelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); - query.andWhere('note.renoteChannelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); + query.andWhere(new Brackets(qb => { + qb.orWhere('note.renoteChannelId IS NULL'); + qb.orWhere('note.renoteChannelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); + })); } } //#endregion diff --git a/packages/backend/src/server/api/endpoints/hashtags/users.ts b/packages/backend/src/server/api/endpoints/hashtags/users.ts index 30f0c1b0c8..7b2c137bd4 100644 --- a/packages/backend/src/server/api/endpoints/hashtags/users.ts +++ b/packages/backend/src/server/api/endpoints/hashtags/users.ts @@ -32,6 +32,7 @@ export const paramDef = { properties: { tag: { type: 'string' }, limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, + offset: { type: 'integer', default: 0 }, sort: { type: 'string', enum: ['+follower', '-follower', '+createdAt', '-createdAt', '+updatedAt', '-updatedAt'] }, state: { type: 'string', enum: ['all', 'alive'], default: 'all' }, origin: { type: 'string', enum: ['combined', 'local', 'remote'], default: 'local' }, @@ -74,7 +75,10 @@ export default class extends Endpoint { // eslint- case '-updatedAt': query.orderBy('user.updatedAt', 'ASC'); break; } - const users = await query.limit(ps.limit).getMany(); + const users = await query + .limit(ps.limit) + .offset(ps.offset) + .getMany(); return await this.userEntityService.packMany(users, me, { schema: 'UserDetailed' }); }); 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 65eece5b97..8dc5cafb56 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 @@ -81,7 +81,7 @@ export default class extends Endpoint { try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts b/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts index 9391aee5e0..050dbaf49e 100644 --- a/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts +++ b/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts @@ -212,7 +212,7 @@ export default class extends Endpoint { try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/2fa/register.ts b/packages/backend/src/server/api/endpoints/i/2fa/register.ts index a54c598213..b6c837eda7 100644 --- a/packages/backend/src/server/api/endpoints/i/2fa/register.ts +++ b/packages/backend/src/server/api/endpoints/i/2fa/register.ts @@ -72,7 +72,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts b/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts index c350136eae..6e5d9943de 100644 --- a/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts +++ b/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts @@ -61,7 +61,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts b/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts index b5a53cc889..23b577dc18 100644 --- a/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts +++ b/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts @@ -57,7 +57,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/change-password.ts b/packages/backend/src/server/api/endpoints/i/change-password.ts index bb78d47149..19ea187ee8 100644 --- a/packages/backend/src/server/api/endpoints/i/change-password.ts +++ b/packages/backend/src/server/api/endpoints/i/change-password.ts @@ -45,7 +45,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/delete-account.ts b/packages/backend/src/server/api/endpoints/i/delete-account.ts index bfa0b4605d..42324c7778 100644 --- a/packages/backend/src/server/api/endpoints/i/delete-account.ts +++ b/packages/backend/src/server/api/endpoints/i/delete-account.ts @@ -49,7 +49,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/import-antennas.ts b/packages/backend/src/server/api/endpoints/i/import-antennas.ts index ccec96ffbb..d888b301a9 100644 --- a/packages/backend/src/server/api/endpoints/i/import-antennas.ts +++ b/packages/backend/src/server/api/endpoints/i/import-antennas.ts @@ -74,7 +74,7 @@ export default class extends Endpoint { super(meta, paramDef, async (ps, me) => { const userExist = await this.usersRepository.exists({ where: { id: me.id } }); if (!userExist) throw new ApiError(meta.errors.noSuchUser); - const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); + const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId, userId: me.id }); if (file === null) throw new ApiError(meta.errors.noSuchFile); if (file.size === 0) throw new ApiError(meta.errors.emptyFile); const antennas: (_Antenna & { userListAccts: string[] | null })[] = JSON.parse(await this.downloadService.downloadTextFile(file.url)); 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 2fa450558b..f8c53e0cb3 100644 --- a/packages/backend/src/server/api/endpoints/i/import-blocking.ts +++ b/packages/backend/src/server/api/endpoints/i/import-blocking.ts @@ -68,7 +68,7 @@ export default class extends Endpoint { // eslint- private accountMoveService: AccountMoveService, ) { super(meta, paramDef, async (ps, me) => { - const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); + const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId, userId: me.id }); if (file == null) throw new ApiError(meta.errors.noSuchFile); //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); 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 9186fca162..f833b992e7 100644 --- a/packages/backend/src/server/api/endpoints/i/import-following.ts +++ b/packages/backend/src/server/api/endpoints/i/import-following.ts @@ -68,7 +68,7 @@ export default class extends Endpoint { // eslint- private accountMoveService: AccountMoveService, ) { super(meta, paramDef, async (ps, me) => { - const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); + const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId, userId: me.id }); if (file == null) throw new ApiError(meta.errors.noSuchFile); //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); 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 b6dbacd371..c0efa6ebe0 100644 --- a/packages/backend/src/server/api/endpoints/i/import-muting.ts +++ b/packages/backend/src/server/api/endpoints/i/import-muting.ts @@ -68,7 +68,7 @@ export default class extends Endpoint { // eslint- private accountMoveService: AccountMoveService, ) { super(meta, paramDef, async (ps, me) => { - const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); + const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId, userId: me.id }); if (file == null) throw new ApiError(meta.errors.noSuchFile); //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); 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 5de0a70bbb..5c60a46efd 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 @@ -67,7 +67,7 @@ export default class extends Endpoint { // eslint- private accountMoveService: AccountMoveService, ) { super(meta, paramDef, async (ps, me) => { - const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId }); + const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId, userId: me.id }); if (file == null) throw new ApiError(meta.errors.noSuchFile); //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); diff --git a/packages/backend/src/server/api/endpoints/i/notifications-grouped.ts b/packages/backend/src/server/api/endpoints/i/notifications-grouped.ts index f933eaab00..4fe39bb8e8 100644 --- a/packages/backend/src/server/api/endpoints/i/notifications-grouped.ts +++ b/packages/backend/src/server/api/endpoints/i/notifications-grouped.ts @@ -71,7 +71,6 @@ export default class extends Endpoint { // eslint- private notificationService: NotificationService, ) { super(meta, paramDef, async (ps, me) => { - const EXTRA_LIMIT = 100; const untilId = ps.untilId ?? (ps.untilDate ? this.idService.gen(ps.untilDate!) : undefined); const sinceId = ps.sinceId ?? (ps.sinceDate ? this.idService.gen(ps.sinceDate!) : undefined); 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 da1faee30d..c2f4281f36 100644 --- a/packages/backend/src/server/api/endpoints/i/update-email.ts +++ b/packages/backend/src/server/api/endpoints/i/update-email.ts @@ -91,7 +91,7 @@ export default class extends Endpoint { // eslint- try { await this.userAuthService.twoFactorAuthenticate(profile, token); - } catch (e) { + } catch (_) { throw new Error('authentication failed'); } } diff --git a/packages/backend/src/server/api/endpoints/i/update.ts b/packages/backend/src/server/api/endpoints/i/update.ts index 9971a1ea4d..5207d9f2b0 100644 --- a/packages/backend/src/server/api/endpoints/i/update.ts +++ b/packages/backend/src/server/api/endpoints/i/update.ts @@ -323,7 +323,7 @@ export default class extends Endpoint { // eslint- try { new RE2(regexp[1], regexp[2]); - } catch (err) { + } catch (_) { throw new ApiError(meta.errors.invalidRegexp); } } @@ -587,7 +587,7 @@ export default class extends Endpoint { // eslint- }) .execute(); } - } catch (err) { + } catch (_) { // なにもしない } } diff --git a/packages/backend/src/server/api/endpoints/notes/polls/vote.ts b/packages/backend/src/server/api/endpoints/notes/polls/vote.ts index f33f49075b..56ddf651df 100644 --- a/packages/backend/src/server/api/endpoints/notes/polls/vote.ts +++ b/packages/backend/src/server/api/endpoints/notes/polls/vote.ts @@ -155,7 +155,7 @@ export default class extends Endpoint { // eslint- const index = ps.choice + 1; // In SQL, array index is 1 based await this.pollsRepository.query(`UPDATE poll SET votes[${index}] = votes[${index}] + 1 WHERE "noteId" = '${poll.noteId}'`); - this.globalEventService.publishNoteStream(note.id, 'pollVoted', { + this.globalEventService.publishNoteStream(note, 'pollVoted', { choice: ps.choice, userId: me.id, }); diff --git a/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts b/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts index 29c6aa7434..7c0dddb827 100644 --- a/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts +++ b/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts @@ -59,7 +59,7 @@ export default class extends Endpoint { // eslint- throw err; }); - const mutedNotes = await this.notesRepository.find({ + const _mutedNotes = await this.notesRepository.find({ where: [{ id: note.threadId ?? note.id, }, { diff --git a/packages/backend/src/server/api/endpoints/notes/timeline.ts b/packages/backend/src/server/api/endpoints/notes/timeline.ts index fe9c412be4..b00247c69d 100644 --- a/packages/backend/src/server/api/endpoints/notes/timeline.ts +++ b/packages/backend/src/server/api/endpoints/notes/timeline.ts @@ -177,7 +177,10 @@ export default class extends Endpoint { // eslint- .andWhere('note.channelId IS NULL') .andWhere('note.userId IN (:...meOrFolloweeIds)', { meOrFolloweeIds: meOrFolloweeIds }); if (mutingChannelIds.length > 0) { - qb.andWhere('note.renoteChannelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); + qb.andWhere(new Brackets(qb2 => { + qb2.orWhere('note.renoteChannelId IS NULL'); + qb2.orWhere('note.renoteChannelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); + })); } })); } else if (followingChannelIds.length > 0) { diff --git a/packages/backend/src/server/api/endpoints/server-info.ts b/packages/backend/src/server/api/endpoints/server-info.ts index 8301c85f2e..0e8dc73ad9 100644 --- a/packages/backend/src/server/api/endpoints/server-info.ts +++ b/packages/backend/src/server/api/endpoints/server-info.ts @@ -4,7 +4,6 @@ */ import * as os from 'node:os'; -import si from 'systeminformation'; import { Inject, Injectable } from '@nestjs/common'; import { Endpoint } from '@/server/api/endpoint-base.js'; import { MiMeta } from '@/models/_.js'; @@ -93,6 +92,8 @@ export default class extends Endpoint { // eslint- }, }; + const si = await import('systeminformation'); + const memStats = await si.mem(); const fsStats = await si.fsSize(); diff --git a/packages/backend/src/server/api/endpoints/users/following.ts b/packages/backend/src/server/api/endpoints/users/following.ts index 047f9a053b..4defcc9dcf 100644 --- a/packages/backend/src/server/api/endpoints/users/following.ts +++ b/packages/backend/src/server/api/endpoints/users/following.ts @@ -86,7 +86,7 @@ export const paramDef = { sinceDate: { type: 'integer' }, untilDate: { type: 'integer' }, limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, - birthday: { ...birthdaySchema, nullable: true }, + birthday: { ...birthdaySchema, nullable: true, description: '@deprecated use get-following-users-by-birthday instead.' }, }, }, ], @@ -146,15 +146,16 @@ export default class extends Endpoint { // eslint- .andWhere('following.followerId = :userId', { userId: user.id }) .innerJoinAndSelect('following.followee', 'followee'); + // @deprecated use get-following-users-by-birthday instead. if (ps.birthday) { - try { - 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}'`); + query.innerJoin(this.userProfilesRepository.metadata.targetName, 'followeeProfile', 'followeeProfile.userId = following.followeeId'); - query.andWhere(`following.followeeId IN (${ birthdayUserQuery.getQuery() })`); - } catch (err) { + try { + const birthday = ps.birthday.split('-'); + birthday.shift(); // 年の部分を削除 + // なぜか get_birthday_date() = :birthday だとインデックスが効かないので、BETWEEN で対応 + query.andWhere('get_birthday_date(followeeProfile.birthday) BETWEEN :birthday AND :birthday', { birthday: parseInt(birthday.join('')) }); + } catch (_) { throw new ApiError(meta.errors.birthdayInvalid); } } diff --git a/packages/backend/src/server/api/endpoints/users/get-following-users-by-birthday.ts b/packages/backend/src/server/api/endpoints/users/get-following-users-by-birthday.ts new file mode 100644 index 0000000000..947c19d81e --- /dev/null +++ b/packages/backend/src/server/api/endpoints/users/get-following-users-by-birthday.ts @@ -0,0 +1,167 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Inject, Injectable } from '@nestjs/common'; +import { Brackets } from 'typeorm'; +import { DI } from '@/di-symbols.js'; +import type { + FollowingsRepository, + UserProfilesRepository, +} from '@/models/_.js'; +import { Endpoint } from '@/server/api/endpoint-base.js'; +import { UserEntityService } from '@/core/entities/UserEntityService.js'; +import type { Packed } from '@/misc/json-schema.js'; + +export const meta = { + tags: ['users'], + + requireCredential: true, + kind: 'read:account', + + description: 'Retrieve users who have a birthday on the specified range.', + + res: { + type: 'array', + optional: false, nullable: false, + items: { + type: 'object', + optional: false, nullable: false, + properties: { + id: { + type: 'string', + optional: false, nullable: false, + format: 'misskey:id', + }, + birthday: { + type: 'string', + optional: false, nullable: false, + }, + user: { + type: 'object', + optional: false, nullable: false, + ref: 'UserLite', + }, + }, + }, + }, +} as const; + +export const paramDef = { + type: 'object', + properties: { + limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 }, + offset: { type: 'integer', default: 0 }, + birthday: { + oneOf: [{ + type: 'object', + properties: { + month: { type: 'integer', minimum: 1, maximum: 12 }, + day: { type: 'integer', minimum: 1, maximum: 31 }, + }, + required: ['month', 'day'], + }, { + type: 'object', + properties: { + begin: { + type: 'object', + properties: { + month: { type: 'integer', minimum: 1, maximum: 12 }, + day: { type: 'integer', minimum: 1, maximum: 31 }, + }, + required: ['month', 'day'], + }, + end: { + type: 'object', + properties: { + month: { type: 'integer', minimum: 1, maximum: 12 }, + day: { type: 'integer', minimum: 1, maximum: 31 }, + }, + required: ['month', 'day'], + }, + }, + required: ['begin', 'end'], + }], + }, + }, + required: ['birthday'], +} as const; + +@Injectable() +export default class extends Endpoint { // eslint-disable-line import/no-default-export + constructor( + @Inject(DI.userProfilesRepository) + private userProfilesRepository: UserProfilesRepository, + @Inject(DI.followingsRepository) + private followingsRepository: FollowingsRepository, + + private userEntityService: UserEntityService, + ) { + super(meta, paramDef, async (ps, me) => { + const query = this.followingsRepository + .createQueryBuilder('following') + .andWhere('following.followerId = :userId', { userId: me.id }) + .innerJoin(this.userProfilesRepository.metadata.targetName, 'followeeProfile', 'followeeProfile.userId = following.followeeId'); + + if (Object.hasOwn(ps.birthday, 'begin') && Object.hasOwn(ps.birthday, 'end')) { + const range = ps.birthday as { begin: { month: number; day: number }; end: { month: number; day: number }; }; + + // 誕生日は mmdd の形式の最大4桁の数字(例: 8月30日 → 830)でインデックスが効くようになっているので、その形式に変換 + const begin = range.begin.month * 100 + range.begin.day; + const end = range.end.month * 100 + range.end.day; + + if (begin <= end) { + query.andWhere('get_birthday_date(followeeProfile.birthday) BETWEEN :begin AND :end', { begin, end }); + } else { + // 12/31 から 1/1 の範囲を取得するために OR で対応 + query.andWhere(new Brackets(qb => { + qb.where('get_birthday_date(followeeProfile.birthday) BETWEEN :begin AND 1231', { begin }); + qb.orWhere('get_birthday_date(followeeProfile.birthday) BETWEEN 101 AND :end', { end }); + })); + } + } else { + const { month, day } = ps.birthday as { month: number; day: number }; + // なぜか get_birthday_date() = :birthday だとインデックスが効かないので、BETWEEN で対応 + query.andWhere('get_birthday_date(followeeProfile.birthday) BETWEEN :birthday AND :birthday', { birthday: month * 100 + day }); + } + + query.select('following.followeeId', 'user_id'); + query.addSelect('get_birthday_date(followeeProfile.birthday)', 'birthday_date'); + query.orderBy('birthday_date', 'ASC'); + + const birthdayUsers = await query + .offset(ps.offset).limit(ps.limit) + .getRawMany<{ birthday_date: number; user_id: string }>(); + + const users = new Map>(( + await this.userEntityService.packMany( + birthdayUsers.map(u => u.user_id), + me, + { schema: 'UserLite' }, + ) + ).map(u => [u.id, u])); + + return birthdayUsers + .map(item => { + const birthday = new Date(); + birthday.setHours(0, 0, 0, 0); + // item.birthday_date は mmdd の形式の最大4桁の数字(例: 8月30日 → 830)で出力されるので、日付に戻してDateオブジェクトに設定 + birthday.setMonth(Math.floor(item.birthday_date / 100) - 1, item.birthday_date % 100); + + if (birthday.getTime() < new Date().setHours(0, 0, 0, 0)) { + birthday.setFullYear(new Date().getFullYear() + 1); + } + + const birthdayStr = `${birthday.getFullYear()}-${(birthday.getMonth() + 1).toString().padStart(2, '0')}-${(birthday.getDate()).toString().padStart(2, '0')}`; + return { + id: item.user_id, + birthday: birthdayStr, + user: users.get(item.user_id), + }; + }) + .filter(item => item.user != null) + .map(item => item as { id: string; birthday: string; user: Packed<'UserLite'> }); + }); + } +} diff --git a/packages/backend/src/server/api/endpoints/users/notes.ts b/packages/backend/src/server/api/endpoints/users/notes.ts index b9710250cf..e280b367f9 100644 --- a/packages/backend/src/server/api/endpoints/users/notes.ts +++ b/packages/backend/src/server/api/endpoints/users/notes.ts @@ -185,7 +185,10 @@ export default class extends Endpoint { // eslint- if (ps.withChannelNotes) { query.andWhere(new Brackets(qb => { if (mutingChannelIds.length > 0) { - qb.andWhere('note.channelId NOT IN (:...mutingChannelIds)', { mutingChannelIds: mutingChannelIds }); + qb.andWhere(new Brackets(qb2 => { + qb2.orWhere('note.channelId IS NULL'); + qb2.orWhere('note.channelId NOT IN (:...mutingChannelIds)', { mutingChannelIds }); + })); } if (!isSelf) { diff --git a/packages/backend/src/server/api/openapi/OpenApiServerService.ts b/packages/backend/src/server/api/openapi/OpenApiServerService.ts index f124aa9f39..24fc46e4ba 100644 --- a/packages/backend/src/server/api/openapi/OpenApiServerService.ts +++ b/packages/backend/src/server/api/openapi/OpenApiServerService.ts @@ -3,16 +3,14 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { fileURLToPath } from 'node:url'; import { Inject, Injectable } from '@nestjs/common'; import type { Config } from '@/config.js'; import { DI } from '@/di-symbols.js'; import { bindThis } from '@/decorators.js'; import { genOpenapiSpec } from './gen-spec.js'; +import { ApiDocPage } from './api-doc.js'; import type { FastifyInstance, FastifyPluginOptions } from 'fastify'; -const staticAssets = fileURLToPath(new URL('../../../../assets/', import.meta.url)); - @Injectable() export class OpenApiServerService { constructor( @@ -25,7 +23,8 @@ export class OpenApiServerService { public createServer(fastify: FastifyInstance, _options: FastifyPluginOptions, done: (err?: Error) => void) { fastify.get('/api-doc', async (_request, reply) => { reply.header('Cache-Control', 'public, max-age=86400'); - return await reply.sendFile('/api-doc.html', staticAssets); + reply.type('text/html; charset=utf-8'); + reply.send(await ApiDocPage()); }); fastify.get('/api.json', (_request, reply) => { reply.header('Cache-Control', 'public, max-age=600'); diff --git a/packages/backend/src/server/api/openapi/api-doc.tsx b/packages/backend/src/server/api/openapi/api-doc.tsx new file mode 100644 index 0000000000..663d9f5be3 --- /dev/null +++ b/packages/backend/src/server/api/openapi/api-doc.tsx @@ -0,0 +1,26 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export function ApiDocPage() { + return ( + <> + {''} + + + + Misskey API + + + + + + + + + + ); +} diff --git a/packages/backend/src/server/api/openapi/schemas.ts b/packages/backend/src/server/api/openapi/schemas.ts index 1cdcbebd1a..0714f61294 100644 --- a/packages/backend/src/server/api/openapi/schemas.ts +++ b/packages/backend/src/server/api/openapi/schemas.ts @@ -9,9 +9,8 @@ import { refs } from '@/misc/json-schema.js'; export function convertSchemaToOpenApiSchema(schema: Schema, type: 'param' | 'res', includeSelfRef: boolean): any { // optional, nullable, refはスキーマ定義に含まれないので分離しておく - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { optional, nullable, ref, selfRef, ..._res }: any = schema; - const res = deepClone(_res); + const { optional, nullable, ref, selfRef, ...res1 }: any = schema; + const res = deepClone(res1); if (schema.type === 'object' && schema.properties) { if (type === 'res') { diff --git a/packages/backend/src/server/api/stream/ChannelsService.ts b/packages/backend/src/server/api/stream/ChannelsService.ts deleted file mode 100644 index c0ef589dea..0000000000 --- a/packages/backend/src/server/api/stream/ChannelsService.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SPDX-FileCopyrightText: syuilo and misskey-project - * SPDX-License-Identifier: AGPL-3.0-only - */ - -import { Injectable } from '@nestjs/common'; -import { bindThis } from '@/decorators.js'; -import { HybridTimelineChannelService } from './channels/hybrid-timeline.js'; -import { LocalTimelineChannelService } from './channels/local-timeline.js'; -import { HomeTimelineChannelService } from './channels/home-timeline.js'; -import { GlobalTimelineChannelService } from './channels/global-timeline.js'; -import { MainChannelService } from './channels/main.js'; -import { ChannelChannelService } from './channels/channel.js'; -import { AdminChannelService } from './channels/admin.js'; -import { ServerStatsChannelService } from './channels/server-stats.js'; -import { QueueStatsChannelService } from './channels/queue-stats.js'; -import { UserListChannelService } from './channels/user-list.js'; -import { AntennaChannelService } from './channels/antenna.js'; -import { DriveChannelService } from './channels/drive.js'; -import { HashtagChannelService } from './channels/hashtag.js'; -import { RoleTimelineChannelService } from './channels/role-timeline.js'; -import { ChatUserChannelService } from './channels/chat-user.js'; -import { ChatRoomChannelService } from './channels/chat-room.js'; -import { ReversiChannelService } from './channels/reversi.js'; -import { ReversiGameChannelService } from './channels/reversi-game.js'; -import { type MiChannelService } from './channel.js'; - -@Injectable() -export class ChannelsService { - constructor( - private mainChannelService: MainChannelService, - private homeTimelineChannelService: HomeTimelineChannelService, - private localTimelineChannelService: LocalTimelineChannelService, - private hybridTimelineChannelService: HybridTimelineChannelService, - private globalTimelineChannelService: GlobalTimelineChannelService, - private userListChannelService: UserListChannelService, - private hashtagChannelService: HashtagChannelService, - private roleTimelineChannelService: RoleTimelineChannelService, - private antennaChannelService: AntennaChannelService, - private channelChannelService: ChannelChannelService, - private driveChannelService: DriveChannelService, - private serverStatsChannelService: ServerStatsChannelService, - private queueStatsChannelService: QueueStatsChannelService, - private adminChannelService: AdminChannelService, - private chatUserChannelService: ChatUserChannelService, - private chatRoomChannelService: ChatRoomChannelService, - private reversiChannelService: ReversiChannelService, - private reversiGameChannelService: ReversiGameChannelService, - ) { - } - - @bindThis - public getChannelService(name: string): MiChannelService { - switch (name) { - case 'main': return this.mainChannelService; - case 'homeTimeline': return this.homeTimelineChannelService; - case 'localTimeline': return this.localTimelineChannelService; - case 'hybridTimeline': return this.hybridTimelineChannelService; - case 'globalTimeline': return this.globalTimelineChannelService; - case 'userList': return this.userListChannelService; - case 'hashtag': return this.hashtagChannelService; - case 'roleTimeline': return this.roleTimelineChannelService; - case 'antenna': return this.antennaChannelService; - case 'channel': return this.channelChannelService; - case 'drive': return this.driveChannelService; - case 'serverStats': return this.serverStatsChannelService; - case 'queueStats': return this.queueStatsChannelService; - case 'admin': return this.adminChannelService; - case 'chatUser': return this.chatUserChannelService; - case 'chatRoom': return this.chatRoomChannelService; - case 'reversi': return this.reversiChannelService; - case 'reversiGame': return this.reversiGameChannelService; - - default: - throw new Error(`no such channel: ${name}`); - } - } -} diff --git a/packages/backend/src/server/api/stream/Connection.ts b/packages/backend/src/server/api/stream/Connection.ts index f5b096f7a4..39eb03a5ae 100644 --- a/packages/backend/src/server/api/stream/Connection.ts +++ b/packages/backend/src/server/api/stream/Connection.ts @@ -4,34 +4,55 @@ */ import * as WebSocket from 'ws'; -import type { MiUser } from '@/models/User.js'; -import type { MiAccessToken } from '@/models/AccessToken.js'; -import type { Packed } from '@/misc/json-schema.js'; -import type { NotificationService } from '@/core/NotificationService.js'; -import { bindThis } from '@/decorators.js'; -import { CacheService } from '@/core/CacheService.js'; -import { MiFollowing, MiUserProfile } from '@/models/_.js'; -import type { GlobalEvents, StreamEventEmitter } from '@/core/GlobalEventService.js'; -import { ChannelFollowingService } from '@/core/ChannelFollowingService.js'; -import { ChannelMutingService } from '@/core/ChannelMutingService.js'; +import { ContextIdFactory, ModuleRef, REQUEST } from '@nestjs/core'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { isJsonObject } from '@/misc/json-value.js'; import type { JsonObject, JsonValue } from '@/misc/json-value.js'; -import type { ChannelsService } from './ChannelsService.js'; -import type { EventEmitter } from 'events'; +import { ChannelMutingService } from '@/core/ChannelMutingService.js'; +import { ChannelFollowingService } from '@/core/ChannelFollowingService.js'; +import type { GlobalEvents, StreamEventEmitter } from '@/core/GlobalEventService.js'; +import { MiFollowing, MiUserProfile } from '@/models/_.js'; +import { CacheService } from '@/core/CacheService.js'; +import { bindThis } from '@/decorators.js'; +import { NotificationService } from '@/core/NotificationService.js'; +import type { MiAccessToken } from '@/models/AccessToken.js'; +import type { MiUser } from '@/models/User.js'; +import { MainChannel } from '@/server/api/stream/channels/main.js'; +import { HomeTimelineChannel } from '@/server/api/stream/channels/home-timeline.js'; +import { LocalTimelineChannel } from '@/server/api/stream/channels/local-timeline.js'; +import { HybridTimelineChannel } from '@/server/api/stream/channels/hybrid-timeline.js'; +import { GlobalTimelineChannel } from '@/server/api/stream/channels/global-timeline.js'; +import { UserListChannel } from '@/server/api/stream/channels/user-list.js'; +import { HashtagChannel } from '@/server/api/stream/channels/hashtag.js'; +import { RoleTimelineChannel } from '@/server/api/stream/channels/role-timeline.js'; +import { AntennaChannel } from '@/server/api/stream/channels/antenna.js'; +import { ChannelChannel } from '@/server/api/stream/channels/channel.js'; +import { DriveChannel } from '@/server/api/stream/channels/drive.js'; +import { ServerStatsChannel } from '@/server/api/stream/channels/server-stats.js'; +import { QueueStatsChannel } from '@/server/api/stream/channels/queue-stats.js'; +import { AdminChannel } from '@/server/api/stream/channels/admin.js'; +import { ChatUserChannel } from '@/server/api/stream/channels/chat-user.js'; +import { ChatRoomChannel } from '@/server/api/stream/channels/chat-room.js'; +import { ReversiChannel } from '@/server/api/stream/channels/reversi.js'; +import { ReversiGameChannel } from '@/server/api/stream/channels/reversi-game.js'; +import type { ChannelRequest } from './channel.js'; +import type { ChannelConstructor } from './channel.js'; import type Channel from './channel.js'; +import type { EventEmitter } from 'events'; const MAX_CHANNELS_PER_CONNECTION = 32; /** * Main stream connection */ -// eslint-disable-next-line import/no-default-export + +@Injectable({ scope: Scope.TRANSIENT }) export default class Connection { public user?: MiUser; public token?: MiAccessToken; private wsConnection: WebSocket.WebSocket; public subscriber: StreamEventEmitter; - private channels: Channel[] = []; + private channels: Map = new Map(); private subscribingNotes: Partial> = {}; public userProfile: MiUserProfile | null = null; public following: Record | undefined> = {}; @@ -45,16 +66,16 @@ export default class Connection { private fetchIntervalId: NodeJS.Timeout | null = null; constructor( - private channelsService: ChannelsService, + private moduleRef: ModuleRef, private notificationService: NotificationService, private cacheService: CacheService, private channelFollowingService: ChannelFollowingService, private channelMutingService: ChannelMutingService, - user: MiUser | null | undefined, - token: MiAccessToken | null | undefined, + @Inject(REQUEST) + request: ConnectionRequest, ) { - if (user) this.user = user; - if (token) this.token = token; + if (request.user) this.user = request.user; + if (request.token) this.token = request.token; } @bindThis @@ -120,7 +141,7 @@ export default class Connection { try { obj = JSON.parse(data.toString()); - } catch (e) { + } catch (_) { return; } @@ -187,6 +208,19 @@ export default class Connection { @bindThis private async onNoteStreamMessage(data: GlobalEvents['note']['payload']) { + // 自分自身ではないかつ + if (data.body.userId !== this.user?.id) { + // 公開範囲が指名で自分が含まれてない + if (data.body.visibility === 'specified' && (this.user == null || !data.body.visibleUserIds.includes(this.user.id))) { + return; + } + + // 公開範囲がフォロワーで自分がフォロワーでない + if (data.body.visibility === 'followers' && !Object.hasOwn(this.following, data.body.userId)) { + return; + } + } + this.sendMessageToWs('noteUpdated', { id: data.body.id, type: data.type, @@ -234,30 +268,49 @@ export default class Connection { * チャンネルに接続 */ @bindThis - public connectChannel(id: string, params: JsonObject | undefined, channel: string, pong = false) { - if (this.channels.length >= MAX_CHANNELS_PER_CONNECTION) { + public async connectChannel(id: string, params: JsonObject | undefined, channel: string, pong = false) { + if (this.channels.has(id)) { + this.disconnectChannel(id); + } + + if (this.channels.size >= MAX_CHANNELS_PER_CONNECTION) { return; } - const channelService = this.channelsService.getChannelService(channel); + const channelConstructor = this.getChannelConstructor(channel); - if (channelService.requireCredential && this.user == null) { + if (channelConstructor.requireCredential && this.user == null) { return; } - if (this.token && ((channelService.kind && !this.token.permission.some(p => p === channelService.kind)) - || (!channelService.kind && channelService.requireCredential))) { + if (this.token && ((channelConstructor.kind && !this.token.permission.some(p => p === channelConstructor.kind)) + || (!channelConstructor.kind && channelConstructor.requireCredential))) { return; } // 共有可能チャンネルに接続しようとしていて、かつそのチャンネルに既に接続していたら無意味なので無視 - if (channelService.shouldShare && this.channels.some(c => c.chName === channel)) { - return; + if (channelConstructor.shouldShare) { + for (const c of this.channels.values()) { + if (c.chName === channel) { + return; + } + } } - const ch: Channel = channelService.create(id, this); - this.channels.push(ch); - ch.init(params ?? {}); + const contextId = ContextIdFactory.create(); + this.moduleRef.registerRequestByContextId({ + id: id, + connection: this, + }, contextId); + const ch: Channel = await this.moduleRef.create(channelConstructor, contextId); + + this.channels.set(ch.id, ch); + const valid = await ch.init(params ?? {}); + if (typeof valid === 'boolean' && !valid) { + // 初期化処理の結果、接続拒否されたので切断 + this.disconnectChannel(id); + return; + } if (pong) { this.sendMessageToWs('connected', { @@ -266,17 +319,44 @@ export default class Connection { } } + @bindThis + public getChannelConstructor(name: string): ChannelConstructor { + switch (name) { + case 'main': return MainChannel; + case 'homeTimeline': return HomeTimelineChannel; + case 'localTimeline': return LocalTimelineChannel; + case 'hybridTimeline': return HybridTimelineChannel; + case 'globalTimeline': return GlobalTimelineChannel; + case 'userList': return UserListChannel; + case 'hashtag': return HashtagChannel; + case 'roleTimeline': return RoleTimelineChannel; + case 'antenna': return AntennaChannel; + case 'channel': return ChannelChannel; + case 'drive': return DriveChannel; + case 'serverStats': return ServerStatsChannel; + case 'queueStats': return QueueStatsChannel; + case 'admin': return AdminChannel; + case 'chatUser': return ChatUserChannel; + case 'chatRoom': return ChatRoomChannel; + case 'reversi': return ReversiChannel; + case 'reversiGame': return ReversiGameChannel; + + default: + throw new Error(`no such channel: ${name}`); + } + } + /** * チャンネルから切断 * @param id チャンネルコネクションID */ @bindThis public disconnectChannel(id: string) { - const channel = this.channels.find(c => c.id === id); + const channel = this.channels.get(id); if (channel) { if (channel.dispose) channel.dispose(); - this.channels = this.channels.filter(c => c.id !== id); + this.channels.delete(id); } } @@ -291,7 +371,7 @@ export default class Connection { if (typeof data.type !== 'string') return; if (typeof data.body === 'undefined') return; - const channel = this.channels.find(c => c.id === data.id); + const channel = this.channels.get(data.id); if (channel != null && channel.onMessage != null) { channel.onMessage(data.type, data.body); } @@ -303,8 +383,13 @@ export default class Connection { @bindThis public dispose() { if (this.fetchIntervalId) clearInterval(this.fetchIntervalId); - for (const c of this.channels.filter(c => c.dispose)) { + for (const c of this.channels.values()) { if (c.dispose) c.dispose(); } } } + +export interface ConnectionRequest { + user: MiUser | null | undefined, + token: MiAccessToken | null | undefined, +} diff --git a/packages/backend/src/server/api/stream/NoteStreamingHidingService.ts b/packages/backend/src/server/api/stream/NoteStreamingHidingService.ts new file mode 100644 index 0000000000..1b86c0ae20 --- /dev/null +++ b/packages/backend/src/server/api/stream/NoteStreamingHidingService.ts @@ -0,0 +1,69 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { Injectable } from '@nestjs/common'; +import { bindThis } from '@/decorators.js'; +import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { deepClone } from '@/misc/clone.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; +import type { Packed } from '@/misc/json-schema.js'; +import type { MiUser } from '@/models/User.js'; + +/** Streamにおいて、ノートを隠す(hideNote)を適用するためのService */ +@Injectable() +export class NoteStreamingHidingService { + constructor( + private noteEntityService: NoteEntityService, + ) {} + + private collectRenoteChain(note: Packed<'Note'>): Packed<'Note'>[] { + const renoteChain: Packed<'Note'>[] = []; + + for (let current: Packed<'Note'> | null | undefined = note; current != null; current = current.renote) { + renoteChain.push(current); + } + + return renoteChain; + } + + /** + * ストリーミング配信用にノートの内容を隠す(あるいはそもそも送信しない)判定及び処理を行う。 + * + * 隠す処理が必要な場合は元のノートをクローンして変更を適用したものを返し、 + * 送信すべきでない場合は `null` を返す。 + * 変更が不要な場合は元のノートの参照をそのまま返す。 + * + * @param note - 処理対象のノート + * @param meId - 閲覧者のユーザー ID (未ログインの場合は `null`) + * @returns 配信するノートオブジェクト、または配信スキップの場合は `null` + */ + @bindThis + public async filter(note: Packed<'Note'>, meId: MiUser['id'] | null): Promise | null> { + const renoteChain = this.collectRenoteChain(note); + const shouldHide = await Promise.all(renoteChain.map(n => this.noteEntityService.shouldHideNote(n, meId))); + + if (!shouldHide.some(h => h)) { + // 隠す必要がない場合は元のノートをそのまま返す + return note; + } + + if (renoteChain.some(n => isRenotePacked(n) && !isQuotePacked(n))) { + // 純粋リノートの場合は配信をスキップする + return null; + } + + const clonedNote = deepClone(note); + let currentCloned = clonedNote; + + for (let i = 0; i < renoteChain.length; i++) { + if (shouldHide[i]) { + this.noteEntityService.hideNote(currentCloned); + } + currentCloned = currentCloned.renote!; + } + + return clonedNote; + } +} diff --git a/packages/backend/src/server/api/stream/channel.ts b/packages/backend/src/server/api/stream/channel.ts index 465ed4238c..010d47a7ff 100644 --- a/packages/backend/src/server/api/stream/channel.ts +++ b/packages/backend/src/server/api/stream/channel.ts @@ -8,6 +8,7 @@ import { isInstanceMuted } from '@/misc/is-instance-muted.js'; import { isUserRelated } from '@/misc/is-user-related.js'; import { isQuotePacked, isRenotePacked } from '@/misc/is-renote.js'; import { isChannelRelated } from '@/misc/is-channel-related.js'; +import type { Awaitable } from '@/types.js'; import type { Packed } from '@/misc/json-schema.js'; import type { JsonObject, JsonValue } from '@/misc/json-value.js'; import type Connection from './Connection.js'; @@ -22,7 +23,7 @@ export default abstract class Channel { public abstract readonly chName: string; public static readonly shouldShare: boolean; public static readonly requireCredential: boolean; - public static readonly kind?: string | null; + public static readonly kind: string | null; protected get user() { return this.connection.user; @@ -64,6 +65,43 @@ export default abstract class Channel { return this.connection.subscriber; } + protected isNoteVisibleForMe(note: Packed<'Note'>): boolean { + // This code must always be synchronized with the checks in QueryService.generateVisibilityQuery. + const meId = this.connection.user?.id ?? null; + + // visibility が specified かつ自分が指定されていなかったら非表示 + if (note.visibility === 'specified') { + if (meId == null) { + return false; + } else if (meId === note.userId) { + return true; + } else { + // 指定されているかどうか + return note.visibleUserIds?.some(id => meId === id) ?? false; + } + } + + // visibility が followers かつ自分が投稿者のフォロワーでなかったら非表示 + if (note.visibility === 'followers') { + if (meId == null) { + return false; + } else if (meId === note.userId) { + return true; + } else if (note.reply && (meId === note.reply.userId)) { + // 自分の投稿に対するリプライ + return true; + } else if (note.mentions && note.mentions.some(id => meId === id)) { + // 自分へのメンション + return true; + } else { + // フォロワーかどうか + return Object.hasOwn(this.following, note.userId); + } + } + + return true; + } + /* * ミュートとブロックされてるを処理する */ @@ -85,9 +123,9 @@ export default abstract class Channel { return false; } - constructor(id: string, connection: Connection) { - this.id = id; - this.connection = connection; + constructor(request: ChannelRequest) { + this.id = request.id; + this.connection = request.connection; } public send(payload: { type: string, body: JsonValue }): void; @@ -104,16 +142,28 @@ export default abstract class Channel { }); } - public abstract init(params: JsonObject): void; + /** + * チャンネルの初期化処理(接続時点での接続可否チェックを兼ねる) + * + * - `void / Promise` を返す場合は、チェックなし + * - `true / Promise` を返す場合は、接続可能 + * - `false / Promise` を返す場合は、接続不可(接続を切断) + */ + public abstract init(params: JsonObject): Awaitable; public dispose?(): void; public onMessage?(type: string, body: JsonValue): void; } -export type MiChannelService = { +export interface ChannelRequest { + id: string, + connection: Connection, +} + +export interface ChannelConstructor { + new(...args: any[]): Channel; shouldShare: boolean; requireCredential: T; kind: T extends true ? string : string | null | undefined; - create: (id: string, connection: Connection) => Channel; -}; +} diff --git a/packages/backend/src/server/api/stream/channels/admin.ts b/packages/backend/src/server/api/stream/channels/admin.ts index 355d5dba21..821888cca0 100644 --- a/packages/backend/src/server/api/stream/channels/admin.ts +++ b/packages/backend/src/server/api/stream/channels/admin.ts @@ -3,17 +3,26 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class AdminChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class AdminChannel extends Channel { public readonly chName = 'admin'; public static shouldShare = true; public static requireCredential = true as const; public static kind = 'read:admin:stream'; + constructor( + @Inject(REQUEST) + request: ChannelRequest, + ) { + super(request); + } + @bindThis public async init(params: JsonObject) { // Subscribe admin stream @@ -22,22 +31,3 @@ class AdminChannel extends Channel { }); } } - -@Injectable() -export class AdminChannelService implements MiChannelService { - public readonly shouldShare = AdminChannel.shouldShare; - public readonly requireCredential = AdminChannel.requireCredential; - public readonly kind = AdminChannel.kind; - - constructor( - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): AdminChannel { - return new AdminChannel( - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/antenna.ts b/packages/backend/src/server/api/stream/channels/antenna.ts index e08562fdf9..b7f863b355 100644 --- a/packages/backend/src/server/api/stream/channels/antenna.ts +++ b/packages/backend/src/server/api/stream/channels/antenna.ts @@ -3,14 +3,20 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; +import { DI } from '@/di-symbols.js'; +import type { AntennasRepository } from '@/models/_.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { GlobalEvents } from '@/core/GlobalEventService.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class AntennaChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class AntennaChannel extends Channel { public readonly chName = 'antenna'; public static shouldShare = false; public static requireCredential = true as const; @@ -18,31 +24,62 @@ class AntennaChannel extends Channel { private antennaId: string; constructor( - private noteEntityService: NoteEntityService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + @Inject(DI.antennasRepository) + private antennasReposiotry: AntennasRepository, + + private noteEntityService: NoteEntityService, + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onEvent = this.onEvent.bind(this); } @bindThis - public async init(params: JsonObject) { - if (typeof params.antennaId !== 'string') return; + public async init(params: JsonObject): Promise { + if (typeof params.antennaId !== 'string') return false; + if (!this.user) return false; + this.antennaId = params.antennaId; + const antennaExists = await this.antennasReposiotry.exists({ + where: { + id: this.antennaId, + userId: this.user.id, + }, + }); + + if (!antennaExists) return false; + // Subscribe stream this.subscriber.on(`antennaStream:${this.antennaId}`, this.onEvent); + + return true; } @bindThis private async onEvent(data: GlobalEvents['antenna']['payload']) { if (data.type === 'note') { - const note = await this.noteEntityService.pack(data.body.id, this.user, { detail: true }); + let note = await this.noteEntityService.pack(data.body.id, this.user, { detail: true }); + if (!this.isNoteVisibleForMe(note)) return; if (this.isNoteMutedOrBlocked(note)) return; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + note = filtered; + + if (this.user) { + if (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; + } + } + } + this.send('note', note); } else { this.send(data.type, data.body); @@ -55,24 +92,3 @@ class AntennaChannel extends Channel { this.subscriber.off(`antennaStream:${this.antennaId}`, this.onEvent); } } - -@Injectable() -export class AntennaChannelService implements MiChannelService { - public readonly shouldShare = AntennaChannel.shouldShare; - public readonly requireCredential = AntennaChannel.requireCredential; - public readonly kind = AntennaChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): AntennaChannel { - return new AntennaChannel( - this.noteEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/channel.ts b/packages/backend/src/server/api/stream/channels/channel.ts index c07eaac98d..6b9159887b 100644 --- a/packages/backend/src/server/api/stream/channels/channel.ts +++ b/packages/backend/src/server/api/stream/channels/channel.ts @@ -3,28 +3,33 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import { isInstanceMuted } from '@/misc/is-instance-muted.js'; import { isUserRelated } from '@/misc/is-user-related.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class ChannelChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ChannelChannel extends Channel { public readonly chName = 'channel'; public static shouldShare = false; public static requireCredential = false as const; private channelId: string; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private noteEntityService: NoteEntityService, - id: string, - connection: Channel['connection'], + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -45,12 +50,20 @@ class ChannelChannel extends Channel { if (note.renote && note.renote.user.requireSigninToViewContents && this.user == null) return; if (note.reply && note.reply.user.requireSigninToViewContents && this.user == null) return; + if (!this.isNoteVisibleForMe(note)) return; if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -92,24 +105,3 @@ class ChannelChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class ChannelChannelService implements MiChannelService { - public readonly shouldShare = ChannelChannel.shouldShare; - public readonly requireCredential = ChannelChannel.requireCredential; - public readonly kind = ChannelChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ChannelChannel { - return new ChannelChannel( - this.noteEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/chat-room.ts b/packages/backend/src/server/api/stream/channels/chat-room.ts index eda333dd30..f56522716e 100644 --- a/packages/backend/src/server/api/stream/channels/chat-room.ts +++ b/packages/backend/src/server/api/stream/channels/chat-room.ts @@ -3,14 +3,18 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; +import { DI } from '@/di-symbols.js'; import { bindThis } from '@/decorators.js'; import type { GlobalEvents } from '@/core/GlobalEventService.js'; import type { JsonObject } from '@/misc/json-value.js'; import { ChatService } from '@/core/ChatService.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; +import type { ChatRoomsRepository } from '@/models/_.js'; -class ChatRoomChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ChatRoomChannel extends Channel { public readonly chName = 'chatRoom'; public static shouldShare = false; public static requireCredential = true as const; @@ -18,20 +22,34 @@ class ChatRoomChannel extends Channel { private roomId: string; constructor( - private chatService: ChatService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + @Inject(DI.chatRoomsRepository) + private chatRoomsRepository: ChatRoomsRepository, + + private chatService: ChatService, ) { - super(id, connection); + super(request); } @bindThis - public async init(params: JsonObject) { - if (typeof params.roomId !== 'string') return; + public async init(params: JsonObject): Promise { + if (typeof params.roomId !== 'string') return false; + if (!this.user) return false; + this.roomId = params.roomId; + const room = await this.chatRoomsRepository.findOneBy({ + id: this.roomId, + }); + + if (room == null) return false; + if (!(await this.chatService.hasPermissionToViewRoomTimeline(this.user.id, room))) return false; + this.subscriber.on(`chatRoomStream:${this.roomId}`, this.onEvent); + + return true; } @bindThis @@ -55,24 +73,3 @@ class ChatRoomChannel extends Channel { this.subscriber.off(`chatRoomStream:${this.roomId}`, this.onEvent); } } - -@Injectable() -export class ChatRoomChannelService implements MiChannelService { - public readonly shouldShare = ChatRoomChannel.shouldShare; - public readonly requireCredential = ChatRoomChannel.requireCredential; - public readonly kind = ChatRoomChannel.kind; - - constructor( - private chatService: ChatService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ChatRoomChannel { - return new ChatRoomChannel( - this.chatService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/chat-user.ts b/packages/backend/src/server/api/stream/channels/chat-user.ts index 5323484ed7..6d96c658ad 100644 --- a/packages/backend/src/server/api/stream/channels/chat-user.ts +++ b/packages/backend/src/server/api/stream/channels/chat-user.ts @@ -3,14 +3,16 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import type { GlobalEvents } from '@/core/GlobalEventService.js'; import type { JsonObject } from '@/misc/json-value.js'; import { ChatService } from '@/core/ChatService.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class ChatUserChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ChatUserChannel extends Channel { public readonly chName = 'chatUser'; public static shouldShare = false; public static requireCredential = true as const; @@ -18,20 +20,25 @@ class ChatUserChannel extends Channel { private otherId: string; constructor( - private chatService: ChatService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + private chatService: ChatService, ) { - super(id, connection); + super(request); } @bindThis - public async init(params: JsonObject) { - if (typeof params.otherId !== 'string') return; + public async init(params: JsonObject): Promise { + if (typeof params.otherId !== 'string') return false; + if (!this.user) return false; + if (params.otherId === this.user.id) return false; + this.otherId = params.otherId; - this.subscriber.on(`chatUserStream:${this.user!.id}-${this.otherId}`, this.onEvent); + this.subscriber.on(`chatUserStream:${this.user.id}-${this.otherId}`, this.onEvent); + + return true; } @bindThis @@ -55,24 +62,3 @@ class ChatUserChannel extends Channel { this.subscriber.off(`chatUserStream:${this.user!.id}-${this.otherId}`, this.onEvent); } } - -@Injectable() -export class ChatUserChannelService implements MiChannelService { - public readonly shouldShare = ChatUserChannel.shouldShare; - public readonly requireCredential = ChatUserChannel.requireCredential; - public readonly kind = ChatUserChannel.kind; - - constructor( - private chatService: ChatService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ChatUserChannel { - return new ChatUserChannel( - this.chatService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/drive.ts b/packages/backend/src/server/api/stream/channels/drive.ts index 03768f3d23..6f2eb2c8f9 100644 --- a/packages/backend/src/server/api/stream/channels/drive.ts +++ b/packages/backend/src/server/api/stream/channels/drive.ts @@ -3,17 +3,26 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class DriveChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class DriveChannel extends Channel { public readonly chName = 'drive'; public static shouldShare = true; public static requireCredential = true as const; public static kind = 'read:account'; + constructor( + @Inject(REQUEST) + request: ChannelRequest, + ) { + super(request); + } + @bindThis public async init(params: JsonObject) { // Subscribe drive stream @@ -22,22 +31,3 @@ class DriveChannel extends Channel { }); } } - -@Injectable() -export class DriveChannelService implements MiChannelService { - public readonly shouldShare = DriveChannel.shouldShare; - public readonly requireCredential = DriveChannel.requireCredential; - public readonly kind = DriveChannel.kind; - - constructor( - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): DriveChannel { - return new DriveChannel( - id, - connection, - ); - } -} 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 d7c781ad12..7d310bd875 100644 --- a/packages/backend/src/server/api/stream/channels/global-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/global-timeline.ts @@ -3,17 +3,20 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class GlobalTimelineChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class GlobalTimelineChannel extends Channel { public readonly chName = 'globalTimeline'; public static shouldShare = false; public static requireCredential = false as const; @@ -21,14 +24,15 @@ class GlobalTimelineChannel extends Channel { private withFiles: boolean; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private metaService: MetaService, private roleService: RoleService, private noteEntityService: NoteEntityService, - - id: string, - connection: Channel['connection'], + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -58,10 +62,17 @@ class GlobalTimelineChannel extends Channel { if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -74,28 +85,3 @@ class GlobalTimelineChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class GlobalTimelineChannelService implements MiChannelService { - public readonly shouldShare = GlobalTimelineChannel.shouldShare; - public readonly requireCredential = GlobalTimelineChannel.requireCredential; - public readonly kind = GlobalTimelineChannel.kind; - - constructor( - private metaService: MetaService, - private roleService: RoleService, - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): GlobalTimelineChannel { - return new GlobalTimelineChannel( - this.metaService, - this.roleService, - this.noteEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/hashtag.ts b/packages/backend/src/server/api/stream/channels/hashtag.ts index c911d63642..ccbe6a610c 100644 --- a/packages/backend/src/server/api/stream/channels/hashtag.ts +++ b/packages/backend/src/server/api/stream/channels/hashtag.ts @@ -3,39 +3,48 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { normalizeForSearch } from '@/misc/normalize-for-search.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; - -class HashtagChannel extends Channel { +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; +@Injectable({ scope: Scope.TRANSIENT }) +export class HashtagChannel extends Channel { public readonly chName = 'hashtag'; public static shouldShare = false; public static requireCredential = false as const; private q: string[][]; constructor( - private noteEntityService: NoteEntityService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + private noteEntityService: NoteEntityService, + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @bindThis - public async init(params: JsonObject) { - if (!Array.isArray(params.q)) return; - if (!params.q.every(x => Array.isArray(x) && x.every(y => typeof y === 'string'))) return; + public async init(params: JsonObject): Promise { + if (!Array.isArray(params.q)) return false; + if (!params.q.every((x): x is string[] => ( + Array.isArray(x) && + x.length >= 1 && + x.every(y => typeof y === 'string') + ))) return false; this.q = params.q; // Subscribe stream this.subscriber.on('notesStream', this.onNote); + + return true; } @bindThis @@ -44,12 +53,23 @@ class HashtagChannel extends Channel { const matched = this.q.some(tags => tags.every(tag => noteTags.includes(normalizeForSearch(tag)))); if (!matched) return; + if (!this.isNoteVisibleForMe(note)) return; + if (note.user.requireSigninToViewContents && this.user == null) return; + if (note.renote && note.renote.user.requireSigninToViewContents && this.user == null) return; + if (note.reply && note.reply.user.requireSigninToViewContents && this.user == null) return; if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -62,24 +82,3 @@ class HashtagChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class HashtagChannelService implements MiChannelService { - public readonly shouldShare = HashtagChannel.shouldShare; - public readonly requireCredential = HashtagChannel.requireCredential; - public readonly kind = HashtagChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): HashtagChannel { - return new HashtagChannel( - this.noteEntityService, - id, - connection, - ); - } -} 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 eb5b4a8c6c..5b6dbb24b0 100644 --- a/packages/backend/src/server/api/stream/channels/home-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/home-timeline.ts @@ -3,15 +3,18 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class HomeTimelineChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class HomeTimelineChannel extends Channel { public readonly chName = 'homeTimeline'; public static shouldShare = false; public static requireCredential = true as const; @@ -20,12 +23,13 @@ class HomeTimelineChannel extends Channel { private withFiles: boolean; constructor( - private noteEntityService: NoteEntityService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + private noteEntityService: NoteEntityService, + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -53,11 +57,7 @@ class HomeTimelineChannel extends Channel { if (!isMe && !Object.hasOwn(this.following, note.userId)) return; } - if (note.visibility === 'followers') { - if (!isMe && !Object.hasOwn(this.following, note.userId)) return; - } else if (note.visibility === 'specified') { - if (!isMe && !note.visibleUserIds!.includes(this.user!.id)) return; - } + if (!this.isNoteVisibleForMe(note)) return; if (note.reply) { const reply = note.reply; @@ -82,10 +82,17 @@ class HomeTimelineChannel extends Channel { if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -98,24 +105,3 @@ class HomeTimelineChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class HomeTimelineChannelService implements MiChannelService { - public readonly shouldShare = HomeTimelineChannel.shouldShare; - public readonly requireCredential = HomeTimelineChannel.requireCredential; - public readonly kind = HomeTimelineChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): HomeTimelineChannel { - return new HomeTimelineChannel( - this.noteEntityService, - id, - connection, - ); - } -} 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 2155e02012..f81e880018 100644 --- a/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts @@ -3,17 +3,20 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class HybridTimelineChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class HybridTimelineChannel extends Channel { public readonly chName = 'hybridTimeline'; public static shouldShare = false; public static requireCredential = true as const; @@ -23,14 +26,15 @@ class HybridTimelineChannel extends Channel { private withFiles: boolean; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private metaService: MetaService, private roleService: RoleService, private noteEntityService: NoteEntityService, - - id: string, - connection: Channel['connection'], + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -73,12 +77,7 @@ class HybridTimelineChannel extends Channel { } } - if (note.visibility === 'followers') { - if (!isMe && !Object.hasOwn(this.following, note.userId)) return; - } else if (note.visibility === 'specified') { - if (!isMe && !note.visibleUserIds!.includes(this.user!.id)) return; - } - + if (!this.isNoteVisibleForMe(note)) return; if (this.isNoteMutedOrBlocked(note)) return; if (note.reply) { @@ -102,10 +101,17 @@ class HybridTimelineChannel extends Channel { } } - if (this.user && note.renoteId && !note.text) { - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -118,28 +124,3 @@ class HybridTimelineChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class HybridTimelineChannelService implements MiChannelService { - public readonly shouldShare = HybridTimelineChannel.shouldShare; - public readonly requireCredential = HybridTimelineChannel.requireCredential; - public readonly kind = HybridTimelineChannel.kind; - - constructor( - private metaService: MetaService, - private roleService: RoleService, - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): HybridTimelineChannel { - return new HybridTimelineChannel( - this.metaService, - this.roleService, - this.noteEntityService, - id, - connection, - ); - } -} 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 3d7ed6acdb..5df9b7902b 100644 --- a/packages/backend/src/server/api/stream/channels/local-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/local-timeline.ts @@ -3,33 +3,37 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { Packed } from '@/misc/json-schema.js'; import { MetaService } from '@/core/MetaService.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; import { isQuotePacked, isRenotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class LocalTimelineChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class LocalTimelineChannel extends Channel { public readonly chName = 'localTimeline'; - public static shouldShare = false; + public static shouldShare = false as const; public static requireCredential = false as const; private withRenotes: boolean; private withReplies: boolean; private withFiles: boolean; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private metaService: MetaService, private roleService: RoleService, private noteEntityService: NoteEntityService, - - id: string, - connection: Channel['connection'], + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -68,10 +72,17 @@ class LocalTimelineChannel extends Channel { if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -84,28 +95,3 @@ class LocalTimelineChannel extends Channel { this.subscriber.off('notesStream', this.onNote); } } - -@Injectable() -export class LocalTimelineChannelService implements MiChannelService { - public readonly shouldShare = LocalTimelineChannel.shouldShare; - public readonly requireCredential = LocalTimelineChannel.requireCredential; - public readonly kind = LocalTimelineChannel.kind; - - constructor( - private metaService: MetaService, - private roleService: RoleService, - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): LocalTimelineChannel { - return new LocalTimelineChannel( - this.metaService, - this.roleService, - this.noteEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/main.ts b/packages/backend/src/server/api/stream/channels/main.ts index 525f24c105..224d9e0d89 100644 --- a/packages/backend/src/server/api/stream/channels/main.ts +++ b/packages/backend/src/server/api/stream/channels/main.ts @@ -3,32 +3,35 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { isInstanceMuted, isUserFromMutedInstance } from '@/misc/is-instance-muted.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class MainChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class MainChannel extends Channel { public readonly chName = 'main'; public static shouldShare = true; public static requireCredential = true as const; public static kind = 'read:account'; constructor( - private noteEntityService: NoteEntityService, + @Inject(REQUEST) + request: ChannelRequest, - id: string, - connection: Channel['connection'], + private noteEntityService: NoteEntityService, ) { - super(id, connection); + super(request); } @bindThis - public async init(params: JsonObject) { - // Subscribe main stream channel - this.subscriber.on(`mainStream:${this.user!.id}`, async data => { + public async init(params: JsonObject): Promise { + if (!this.user) return false; + + this.subscriber.on(`mainStream:${this.user.id}`, async data => { switch (data.type) { case 'notification': { // Ignore notifications from instances the user has muted @@ -45,8 +48,8 @@ class MainChannel extends Channel { } case 'mention': { if (isInstanceMuted(data.body, new Set(this.userProfile?.mutedInstances ?? []))) return; - - if (this.userIdsWhoMeMuting.has(data.body.userId)) return; + if (!this.isNoteVisibleForMe(data.body)) return; + if (this.isNoteMutedOrBlocked(data.body)) return; if (data.body.isHidden) { const note = await this.noteEntityService.pack(data.body.id, this.user, { detail: true, @@ -59,26 +62,7 @@ class MainChannel extends Channel { this.send(data.type, data.body); }); - } -} - -@Injectable() -export class MainChannelService implements MiChannelService { - public readonly shouldShare = MainChannel.shouldShare; - public readonly requireCredential = MainChannel.requireCredential; - public readonly kind = MainChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): MainChannel { - return new MainChannel( - this.noteEntityService, - id, - connection, - ); + + return true; } } diff --git a/packages/backend/src/server/api/stream/channels/queue-stats.ts b/packages/backend/src/server/api/stream/channels/queue-stats.ts index 91b62255b4..a87863f26c 100644 --- a/packages/backend/src/server/api/stream/channels/queue-stats.ts +++ b/packages/backend/src/server/api/stream/channels/queue-stats.ts @@ -4,21 +4,26 @@ */ import Xev from 'xev'; -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import { isJsonObject } from '@/misc/json-value.js'; import type { JsonObject, JsonValue } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; const ev = new Xev(); -class QueueStatsChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class QueueStatsChannel extends Channel { public readonly chName = 'queueStats'; public static shouldShare = true; public static requireCredential = false as const; - constructor(id: string, connection: Channel['connection']) { - super(id, connection); + constructor( + @Inject(REQUEST) + request: ChannelRequest, + ) { + super(request); //this.onStats = this.onStats.bind(this); //this.onMessage = this.onMessage.bind(this); } @@ -56,22 +61,3 @@ class QueueStatsChannel extends Channel { ev.removeListener('queueStats', this.onStats); } } - -@Injectable() -export class QueueStatsChannelService implements MiChannelService { - public readonly shouldShare = QueueStatsChannel.shouldShare; - public readonly requireCredential = QueueStatsChannel.requireCredential; - public readonly kind = QueueStatsChannel.kind; - - constructor( - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): QueueStatsChannel { - return new QueueStatsChannel( - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/reversi-game.ts b/packages/backend/src/server/api/stream/channels/reversi-game.ts index 7597a1cfa3..58fc16e98c 100644 --- a/packages/backend/src/server/api/stream/channels/reversi-game.ts +++ b/packages/backend/src/server/api/stream/channels/reversi-game.ts @@ -3,31 +3,32 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Inject, Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { MiReversiGame } from '@/models/_.js'; -import { DI } from '@/di-symbols.js'; import { bindThis } from '@/decorators.js'; import { ReversiService } from '@/core/ReversiService.js'; import { ReversiGameEntityService } from '@/core/entities/ReversiGameEntityService.js'; import { isJsonObject } from '@/misc/json-value.js'; import type { JsonObject, JsonValue } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; import { reversiUpdateKeys } from 'misskey-js'; +import { REQUEST } from '@nestjs/core'; -class ReversiGameChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ReversiGameChannel extends Channel { public readonly chName = 'reversiGame'; public static shouldShare = false; public static requireCredential = false as const; private gameId: MiReversiGame['id'] | null = null; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private reversiService: ReversiService, private reversiGameEntityService: ReversiGameEntityService, - - id: string, - connection: Channel['connection'], ) { - super(id, connection); + super(request); } @bindThis @@ -107,25 +108,3 @@ class ReversiGameChannel extends Channel { } } -@Injectable() -export class ReversiGameChannelService implements MiChannelService { - public readonly shouldShare = ReversiGameChannel.shouldShare; - public readonly requireCredential = ReversiGameChannel.requireCredential; - public readonly kind = ReversiGameChannel.kind; - - constructor( - private reversiService: ReversiService, - private reversiGameEntityService: ReversiGameEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ReversiGameChannel { - return new ReversiGameChannel( - this.reversiService, - this.reversiGameEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/reversi.ts b/packages/backend/src/server/api/stream/channels/reversi.ts index 6e88939724..5eff73eeef 100644 --- a/packages/backend/src/server/api/stream/channels/reversi.ts +++ b/packages/backend/src/server/api/stream/channels/reversi.ts @@ -3,22 +3,24 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class ReversiChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ReversiChannel extends Channel { public readonly chName = 'reversi'; public static shouldShare = true; public static requireCredential = true as const; public static kind = 'read:account'; constructor( - id: string, - connection: Channel['connection'], + @Inject(REQUEST) + request: ChannelRequest, ) { - super(id, connection); + super(request); } @bindThis @@ -32,22 +34,3 @@ class ReversiChannel extends Channel { this.subscriber.off(`reversiStream:${this.user!.id}`, this.send); } } - -@Injectable() -export class ReversiChannelService implements MiChannelService { - public readonly shouldShare = ReversiChannel.shouldShare; - public readonly requireCredential = ReversiChannel.requireCredential; - public readonly kind = ReversiChannel.kind; - - constructor( - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ReversiChannel { - return new ReversiChannel( - id, - connection, - ); - } -} 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 fcfa26c38b..c0e054b3e7 100644 --- a/packages/backend/src/server/api/stream/channels/role-timeline.ts +++ b/packages/backend/src/server/api/stream/channels/role-timeline.ts @@ -3,28 +3,33 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; import { bindThis } from '@/decorators.js'; import { RoleService } from '@/core/RoleService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; +import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { GlobalEvents } from '@/core/GlobalEventService.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class RoleTimelineChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class RoleTimelineChannel extends Channel { public readonly chName = 'roleTimeline'; public static shouldShare = false; public static requireCredential = false as const; private roleId: string; constructor( + @Inject(REQUEST) + request: ChannelRequest, + private noteEntityService: NoteEntityService, private roleservice: RoleService, - - id: string, - connection: Channel['connection'], + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.onNote = this.onNote.bind(this); } @@ -39,15 +44,31 @@ class RoleTimelineChannel extends Channel { @bindThis private async onEvent(data: GlobalEvents['roleTimeline']['payload']) { if (data.type === 'note') { - const note = data.body; + let note = data.body; if (!(await this.roleservice.isExplorable({ id: this.roleId }))) { return; } if (note.visibility !== 'public') return; + if (note.user.requireSigninToViewContents && this.user == null) return; + if (note.renote && note.renote.user.requireSigninToViewContents && this.user == null) return; + if (note.reply && note.reply.user.requireSigninToViewContents && this.user == null) return; if (this.isNoteMutedOrBlocked(note)) return; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + note = filtered; + + if (this.user) { + if (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; + } + } + } + this.send('note', note); } else { this.send(data.type, data.body); @@ -60,26 +81,3 @@ class RoleTimelineChannel extends Channel { this.subscriber.off(`roleTimelineStream:${this.roleId}`, this.onEvent); } } - -@Injectable() -export class RoleTimelineChannelService implements MiChannelService { - public readonly shouldShare = RoleTimelineChannel.shouldShare; - public readonly requireCredential = RoleTimelineChannel.requireCredential; - public readonly kind = RoleTimelineChannel.kind; - - constructor( - private noteEntityService: NoteEntityService, - private roleservice: RoleService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): RoleTimelineChannel { - return new RoleTimelineChannel( - this.noteEntityService, - this.roleservice, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/api/stream/channels/server-stats.ts b/packages/backend/src/server/api/stream/channels/server-stats.ts index ec5352d12d..aece5435b0 100644 --- a/packages/backend/src/server/api/stream/channels/server-stats.ts +++ b/packages/backend/src/server/api/stream/channels/server-stats.ts @@ -4,21 +4,26 @@ */ import Xev from 'xev'; -import { Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import { bindThis } from '@/decorators.js'; import { isJsonObject } from '@/misc/json-value.js'; import type { JsonObject, JsonValue } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; const ev = new Xev(); -class ServerStatsChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class ServerStatsChannel extends Channel { public readonly chName = 'serverStats'; public static shouldShare = true; public static requireCredential = false as const; - constructor(id: string, connection: Channel['connection']) { - super(id, connection); + constructor( + @Inject(REQUEST) + request: ChannelRequest, + ) { + super(request); //this.onStats = this.onStats.bind(this); //this.onMessage = this.onMessage.bind(this); } @@ -54,22 +59,3 @@ class ServerStatsChannel extends Channel { ev.removeListener('serverStats', this.onStats); } } - -@Injectable() -export class ServerStatsChannelService implements MiChannelService { - public readonly shouldShare = ServerStatsChannel.shouldShare; - public readonly requireCredential = ServerStatsChannel.requireCredential; - public readonly kind = ServerStatsChannel.kind; - - constructor( - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): ServerStatsChannel { - return new ServerStatsChannel( - id, - connection, - ); - } -} 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 5bfd8fa68c..0a9d09d64a 100644 --- a/packages/backend/src/server/api/stream/channels/user-list.ts +++ b/packages/backend/src/server/api/stream/channels/user-list.ts @@ -3,17 +3,20 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { Inject, Injectable } from '@nestjs/common'; +import { Inject, Injectable, Scope } from '@nestjs/common'; import type { MiUserListMembership, UserListMembershipsRepository, UserListsRepository } from '@/models/_.js'; import type { Packed } from '@/misc/json-schema.js'; import { NoteEntityService } from '@/core/entities/NoteEntityService.js'; +import { NoteStreamingHidingService } from '../NoteStreamingHidingService.js'; import { DI } from '@/di-symbols.js'; import { bindThis } from '@/decorators.js'; import { isRenotePacked, isQuotePacked } from '@/misc/is-renote.js'; import type { JsonObject } from '@/misc/json-value.js'; -import Channel, { type MiChannelService } from '../channel.js'; +import Channel, { type ChannelRequest } from '../channel.js'; +import { REQUEST } from '@nestjs/core'; -class UserListChannel extends Channel { +@Injectable({ scope: Scope.TRANSIENT }) +export class UserListChannel extends Channel { public readonly chName = 'userList'; public static shouldShare = false; public static requireCredential = false as const; @@ -24,21 +27,26 @@ class UserListChannel extends Channel { private withRenotes: boolean; constructor( + @Inject(DI.userListsRepository) private userListsRepository: UserListsRepository, - private userListMembershipsRepository: UserListMembershipsRepository, - private noteEntityService: NoteEntityService, - id: string, - connection: Channel['connection'], + @Inject(DI.userListMembershipsRepository) + private userListMembershipsRepository: UserListMembershipsRepository, + + @Inject(REQUEST) + request: ChannelRequest, + + private noteEntityService: NoteEntityService, + private noteStreamingHidingService: NoteStreamingHidingService, ) { - super(id, connection); + super(request); //this.updateListUsers = this.updateListUsers.bind(this); //this.onNote = this.onNote.bind(this); } @bindThis - public async init(params: JsonObject) { - if (typeof params.listId !== 'string') return; + public async init(params: JsonObject): Promise { + if (typeof params.listId !== 'string') return false; this.listId = params.listId; this.withFiles = !!(params.withFiles ?? false); this.withRenotes = !!(params.withRenotes ?? true); @@ -50,7 +58,7 @@ class UserListChannel extends Channel { userId: this.user!.id, }, }); - if (!listExist) return; + if (!listExist) return false; // Subscribe stream this.subscriber.on(`userListStream:${this.listId}`, this.send); @@ -59,6 +67,8 @@ class UserListChannel extends Channel { this.updateListUsers(); this.listUsersClock = setInterval(this.updateListUsers, 5000); + + return true; } @bindThis @@ -90,11 +100,7 @@ class UserListChannel extends Channel { if (!Object.hasOwn(this.membershipsMap, note.userId)) return; - if (note.visibility === 'followers') { - if (!isMe && !Object.hasOwn(this.following, note.userId)) return; - } else if (note.visibility === 'specified') { - if (!note.visibleUserIds!.includes(this.user!.id)) return; - } + if (!this.isNoteVisibleForMe(note)) return; if (note.reply) { const reply = note.reply; @@ -111,10 +117,17 @@ class UserListChannel extends Channel { if (this.isNoteMutedOrBlocked(note)) return; - 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; + const filtered = await this.noteStreamingHidingService.filter(note, this.user?.id ?? null); + if (!filtered) return; + // eslint-disable-next-line no-param-reassign -- これ以降元の Note オブジェクトは見てはいけないので、いっそ再代入した方が安全 + note = filtered; + + if (this.user) { + if (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; + } } } @@ -130,32 +143,3 @@ class UserListChannel extends Channel { clearInterval(this.listUsersClock); } } - -@Injectable() -export class UserListChannelService implements MiChannelService { - public readonly shouldShare = UserListChannel.shouldShare; - public readonly requireCredential = UserListChannel.requireCredential; - public readonly kind = UserListChannel.kind; - - constructor( - @Inject(DI.userListsRepository) - private userListsRepository: UserListsRepository, - - @Inject(DI.userListMembershipsRepository) - private userListMembershipsRepository: UserListMembershipsRepository, - - private noteEntityService: NoteEntityService, - ) { - } - - @bindThis - public create(id: string, connection: Channel['connection']): UserListChannel { - return new UserListChannel( - this.userListsRepository, - this.userListMembershipsRepository, - this.noteEntityService, - id, - connection, - ); - } -} diff --git a/packages/backend/src/server/file/FileServerDriveHandler.ts b/packages/backend/src/server/file/FileServerDriveHandler.ts new file mode 100644 index 0000000000..51b527b146 --- /dev/null +++ b/packages/backend/src/server/file/FileServerDriveHandler.ts @@ -0,0 +1,116 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import * as fs from 'node:fs'; +import rename from 'rename'; +import type { Config } from '@/config.js'; +import type { IImageStreamable } from '@/core/ImageProcessingService.js'; +import { contentDisposition } from '@/misc/content-disposition.js'; +import { correctFilename } from '@/misc/correct-filename.js'; +import { isMimeImage } from '@/misc/is-mime-image.js'; +import { VideoProcessingService } from '@/core/VideoProcessingService.js'; +import { attachStreamCleanup, handleRangeRequest, setFileResponseHeaders, getSafeContentType, needsCleanup } from './FileServerUtils.js'; +import type { FileServerFileResolver } from './FileServerFileResolver.js'; +import type { FastifyReply, FastifyRequest } from 'fastify'; + +export class FileServerDriveHandler { + constructor( + private config: Config, + private fileResolver: FileServerFileResolver, + private assetsPath: string, + private videoProcessingService: VideoProcessingService, + ) {} + + public async handle(request: FastifyRequest<{ Params: { key: string } }>, reply: FastifyReply) { + const key = request.params.key; + const file = await this.fileResolver.resolveFileByAccessKey(key); + + if (file.kind === 'not-found') { + reply.code(404); + reply.header('Cache-Control', 'max-age=86400'); + return reply.sendFile('/dummy.png', this.assetsPath); + } + + if (file.kind === 'unavailable') { + reply.code(204); + reply.header('Cache-Control', 'max-age=86400'); + return; + } + + try { + if (file.kind === 'remote') { + let image: IImageStreamable | null = null; + + if (file.fileRole === 'thumbnail') { + if (isMimeImage(file.mime, 'sharp-convertible-image-with-bmp')) { + reply.header('Cache-Control', 'max-age=31536000, immutable'); + + const url = new URL(`${this.config.mediaProxy}/static.webp`); + url.searchParams.set('url', file.url); + url.searchParams.set('static', '1'); + + file.cleanup(); + return await reply.redirect(url.toString(), 301); + } else if (file.mime.startsWith('video/')) { + const externalThumbnail = this.videoProcessingService.getExternalVideoThumbnailUrl(file.url); + if (externalThumbnail) { + file.cleanup(); + return await reply.redirect(externalThumbnail, 301); + } + + image = await this.videoProcessingService.generateVideoThumbnail(file.path); + } + } + + if (file.fileRole === 'webpublic') { + if (['image/svg+xml'].includes(file.mime)) { + reply.header('Cache-Control', 'max-age=31536000, immutable'); + + const url = new URL(`${this.config.mediaProxy}/svg.webp`); + url.searchParams.set('url', file.url); + + file.cleanup(); + return await reply.redirect(url.toString(), 301); + } + } + + image ??= { + data: handleRangeRequest(reply, request.headers.range as string | undefined, file.file.size, file.path), + ext: file.ext, + type: file.mime, + }; + + attachStreamCleanup(image.data, file.cleanup); + + reply.header('Content-Type', getSafeContentType(image.type)); + reply.header('Content-Length', file.file.size); + reply.header('Cache-Control', 'max-age=31536000, immutable'); + reply.header('Content-Disposition', + contentDisposition( + 'inline', + correctFilename(file.filename, image.ext), + ), + ); + return image.data; + } + + if (file.fileRole !== 'original') { + const filename = rename(file.filename, { + suffix: file.fileRole === 'thumbnail' ? '-thumb' : '-web', + extname: file.ext ? `.${file.ext}` : '.unknown', + }).toString(); + + setFileResponseHeaders(reply, { mime: file.mime, filename }); + return handleRangeRequest(reply, request.headers.range as string | undefined, file.file.size, file.path); + } else { + setFileResponseHeaders(reply, { mime: file.file.type, filename: file.filename, size: file.file.size }); + return handleRangeRequest(reply, request.headers.range as string | undefined, file.file.size, file.path); + } + } catch (e) { + if (file.kind === 'remote') file.cleanup(); + throw e; + } + } +} diff --git a/packages/backend/src/server/file/FileServerFileResolver.ts b/packages/backend/src/server/file/FileServerFileResolver.ts new file mode 100644 index 0000000000..687d486efd --- /dev/null +++ b/packages/backend/src/server/file/FileServerFileResolver.ts @@ -0,0 +1,126 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import * as fs from 'node:fs'; +import type { DriveFilesRepository, MiDriveFile } from '@/models/_.js'; +import { createTemp } from '@/misc/create-temp.js'; +import type { DownloadService } from '@/core/DownloadService.js'; +import type { FileInfoService } from '@/core/FileInfoService.js'; +import type { InternalStorageService } from '@/core/InternalStorageService.js'; + +export type DownloadedFileResult = { + kind: 'downloaded'; + mime: string; + ext: string | null; + path: string; + cleanup: () => void; + filename: string; +}; + +export type FileResolveResult = + | { kind: 'not-found' } + | { kind: 'unavailable' } + | { + kind: 'stored'; + fileRole: 'thumbnail' | 'webpublic' | 'original'; + file: MiDriveFile; + filename: string; + mime: string; + ext: string | null; + path: string; + } + | { + kind: 'remote'; + fileRole: 'thumbnail' | 'webpublic' | 'original'; + file: MiDriveFile; + filename: string; + url: string; + mime: string; + ext: string | null; + path: string; + cleanup: () => void; + }; + +export class FileServerFileResolver { + constructor( + private driveFilesRepository: DriveFilesRepository, + private fileInfoService: FileInfoService, + private downloadService: DownloadService, + private internalStorageService: InternalStorageService, + ) {} + + public async downloadAndDetectTypeFromUrl(url: string): Promise { + const [path, cleanup] = await createTemp(); + try { + const { filename } = await this.downloadService.downloadUrl(url, path); + + const { mime, ext } = await this.fileInfoService.detectType(path); + + return { + kind: 'downloaded', + mime, ext, + path, cleanup, + filename, + }; + } catch (e) { + cleanup(); + throw e; + } + } + + public async resolveFileByAccessKey(key: string): Promise { + // Fetch drive file + const file = await this.driveFilesRepository.createQueryBuilder('file') + .where('file.accessKey = :accessKey', { accessKey: key }) + .orWhere('file.thumbnailAccessKey = :thumbnailAccessKey', { thumbnailAccessKey: key }) + .orWhere('file.webpublicAccessKey = :webpublicAccessKey', { webpublicAccessKey: key }) + .getOne(); + + if (file == null) return { kind: 'not-found' }; + + const isThumbnail = file.thumbnailAccessKey === key; + const isWebpublic = file.webpublicAccessKey === key; + + if (!file.storedInternal) { + if (!(file.isLink && file.uri)) return { kind: 'unavailable' }; + const result = await this.downloadAndDetectTypeFromUrl(file.uri); + const { kind: _kind, ...downloaded } = result; + file.size = (await fs.promises.stat(downloaded.path)).size; // DB file.sizeは正確とは限らないので + return { + kind: 'remote', + ...downloaded, + url: file.uri, + fileRole: isThumbnail ? 'thumbnail' : isWebpublic ? 'webpublic' : 'original', + file, + filename: file.name, + }; + } + + const path = this.internalStorageService.resolvePath(key); + + if (isThumbnail || isWebpublic) { + const { mime, ext } = await this.fileInfoService.detectType(path); + return { + kind: 'stored', + fileRole: isThumbnail ? 'thumbnail' : 'webpublic', + file, + filename: file.name, + mime, ext, + path, + }; + } + + return { + kind: 'stored', + fileRole: 'original', + file, + filename: file.name, + // 古いファイルは修正前のmimeを持っているのでできるだけ修正してあげる + mime: this.fileInfoService.fixMime(file.type), + ext: null, + path, + }; + } +} diff --git a/packages/backend/src/server/file/FileServerProxyHandler.ts b/packages/backend/src/server/file/FileServerProxyHandler.ts new file mode 100644 index 0000000000..41e8e47ba5 --- /dev/null +++ b/packages/backend/src/server/file/FileServerProxyHandler.ts @@ -0,0 +1,272 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import * as fs from 'node:fs'; +import sharp from 'sharp'; +import { sharpBmp } from '@misskey-dev/sharp-read-bmp'; +import type { Config } from '@/config.js'; +import { FILE_TYPE_BROWSERSAFE } from '@/const.js'; +import { StatusError } from '@/misc/status-error.js'; +import { contentDisposition } from '@/misc/content-disposition.js'; +import { correctFilename } from '@/misc/correct-filename.js'; +import { isMimeImage } from '@/misc/is-mime-image.js'; +import { IImageStreamable, ImageProcessingService, webpDefault } from '@/core/ImageProcessingService.js'; +import { createRangeStream, attachStreamCleanup, needsCleanup } from './FileServerUtils.js'; +import type { DownloadedFileResult, FileResolveResult, FileServerFileResolver } from './FileServerFileResolver.js'; +import type { FastifyReply, FastifyRequest } from 'fastify'; + +type ProxySource = DownloadedFileResult | FileResolveResult; +type CleanupableFile = ProxySource & { cleanup: () => void }; +type AvailableFile = Exclude; +type ProxyQuery = { + emoji?: string; + avatar?: string; + static?: string; + preview?: string; + badge?: string; + origin?: string; + url?: string; +}; + +export class FileServerProxyHandler { + constructor( + private config: Config, + private fileResolver: FileServerFileResolver, + private assetsPath: string, + private imageProcessingService: ImageProcessingService, + ) {} + + public async handle(request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>, reply: FastifyReply) { + const url = 'url' in request.query ? request.query.url : 'https://' + request.params.url; + + if (typeof url !== 'string') { + reply.code(400); + return; + } + + // アバタークロップなど、どうしてもオリジンである必要がある場合 + const mustOrigin = 'origin' in request.query; + + if (this.config.externalMediaProxyEnabled && !mustOrigin) { + return await this.redirectToExternalProxy(request, reply); + } + + this.validateUserAgent(request); + + // Create temp file + const file = await this.getStreamAndTypeFromUrl(url); + if (file.kind === 'not-found') { + reply.code(404); + reply.header('Cache-Control', 'max-age=86400'); + return reply.sendFile('/dummy.png', this.assetsPath); + } + + if (file.kind === 'unavailable') { + reply.code(204); + reply.header('Cache-Control', 'max-age=86400'); + return; + } + + try { + const image = await this.processImage(file, request, reply); + + if (needsCleanup(file)) { + attachStreamCleanup(image.data, file.cleanup); + } + + reply.header('Content-Type', image.type); + reply.header('Cache-Control', 'max-age=31536000, immutable'); + reply.header('Content-Disposition', + contentDisposition( + 'inline', + correctFilename(file.filename, image.ext), + ), + ); + return image.data; + } catch (e) { + if (needsCleanup(file)) file.cleanup(); + throw e; + } + } + + /** + * 外部メディアプロキシにリダイレクトする + */ + private async redirectToExternalProxy( + request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>, + reply: FastifyReply, + ) { + reply.header('Cache-Control', 'public, max-age=259200'); // 3 days + + const url = new URL(`${this.config.mediaProxy}/${request.params.url || ''}`); + + for (const [key, value] of Object.entries(request.query)) { + url.searchParams.append(key, value); + } + + return reply.redirect(url.toString(), 301); + } + + /** + * User-Agent を検証する + */ + private validateUserAgent(request: FastifyRequest): void { + if (!request.headers['user-agent']) { + throw new StatusError('User-Agent is required', 400, 'User-Agent is required'); + } + if (request.headers['user-agent'].toLowerCase().indexOf('misskey/') !== -1) { + throw new StatusError('Refusing to proxy a request from another proxy', 403, 'Proxy is recursive'); + } + } + + /** + * 画像を処理してストリーム可能な形式に変換する + */ + private async processImage( + file: AvailableFile, + request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>, + reply: FastifyReply, + ): Promise { + const query = request.query; + + const requiresImageConversion = 'emoji' in query || 'avatar' in query || 'static' in query || 'preview' in query || 'badge' in query; + const isConvertibleImage = isMimeImage(file.mime, 'sharp-convertible-image-with-bmp'); + if (requiresImageConversion && !isConvertibleImage) { + throw new StatusError('Unexpected mime', 404); + } + + if ('emoji' in query || 'avatar' in query) { + return this.processEmojiOrAvatar(file, query); + } + + if ('static' in query) { + return this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 498, 422); + } + + if ('preview' in query) { + return this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 200, 200); + } + + if ('badge' in query) { + return this.processBadge(file); + } + + if (file.mime === 'image/svg+xml') { + return this.imageProcessingService.convertToWebpStream(file.path, 2048, 2048); + } + + if (!file.mime.startsWith('image/') || !FILE_TYPE_BROWSERSAFE.includes(file.mime)) { + throw new StatusError('Rejected type', 403, 'Rejected type'); + } + + return this.createDefaultStream(file, request, reply); + } + + /** + * 絵文字またはアバター用の画像を処理する + */ + private async processEmojiOrAvatar( + file: AvailableFile, + query: Pick, + ): Promise { + const isAnimationConvertibleImage = isMimeImage(file.mime, 'sharp-animation-convertible-image-with-bmp'); + if (!isAnimationConvertibleImage && !('static' in query)) { + return { + data: fs.createReadStream(file.path), + ext: file.ext, + type: file.mime, + }; + } + + const data = (await sharpBmp(file.path, file.mime, { animated: !('static' in query) })) + .resize({ + height: 'emoji' in query ? 128 : 320, + withoutEnlargement: true, + }) + .webp(webpDefault); + + return { + data, + ext: 'webp', + type: 'image/webp', + }; + } + + /** + * バッジ用の画像を処理する + */ + private async processBadge(file: AvailableFile): Promise { + const mask = (await sharpBmp(file.path, file.mime)) + .resize(96, 96, { + fit: 'contain', + position: 'centre', + withoutEnlargement: false, + }) + .greyscale() + .normalise() + .linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast + .flatten({ background: '#000' }) + .toColorspace('b-w'); + + const stats = await mask.clone().stats(); + + if (stats.entropy < 0.1) { + throw new StatusError('Skip to provide badge', 404); + } + + const data = sharp({ + create: { width: 96, height: 96, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } }, + }) + .pipelineColorspace('b-w') + .boolean(await mask.png().toBuffer(), 'eor'); + + return { + data: await data.png().toBuffer(), + ext: 'png', + type: 'image/png', + }; + } + + /** + * デフォルトのストリームを作成する(Range リクエスト対応) + */ + private createDefaultStream( + file: AvailableFile, + request: FastifyRequest, + reply: FastifyReply, + ): IImageStreamable { + if (request.headers.range && 'file' in file && file.file.size > 0) { + const { stream, start, end, chunksize } = createRangeStream(request.headers.range as string, file.file.size, file.path); + + reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`); + reply.header('Accept-Ranges', 'bytes'); + reply.header('Content-Length', chunksize); + reply.code(206); + + return { + data: stream, + ext: file.ext, + type: file.mime, + }; + } + + return { + data: fs.createReadStream(file.path), + ext: file.ext, + type: file.mime, + }; + } + + private async getStreamAndTypeFromUrl(url: string): Promise { + if (url.startsWith(`${this.config.url}/files/`)) { + const key = url.replace(`${this.config.url}/files/`, '').split('/').shift(); + if (!key) throw new StatusError('Invalid File Key', 400, 'Invalid File Key'); + + return await this.fileResolver.resolveFileByAccessKey(key); + } + + return await this.fileResolver.downloadAndDetectTypeFromUrl(url); + } +} diff --git a/packages/backend/src/server/file/FileServerUtils.ts b/packages/backend/src/server/file/FileServerUtils.ts new file mode 100644 index 0000000000..c5995a2cca --- /dev/null +++ b/packages/backend/src/server/file/FileServerUtils.ts @@ -0,0 +1,107 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import * as fs from 'node:fs'; +import { FILE_TYPE_BROWSERSAFE } from '@/const.js'; +import { contentDisposition } from '@/misc/content-disposition.js'; +import type { IImageStreamable } from '@/core/ImageProcessingService.js'; +import type { FastifyReply } from 'fastify'; + +export type RangeStream = { + stream: fs.ReadStream; + start: number; + end: number; + chunksize: number; +}; + +/** + * Range リクエストに対応したストリームを作成する + */ +export function createRangeStream(rangeHeader: string, size: number, path: string): RangeStream { + const parts = rangeHeader.replace(/bytes=/, '').split('-'); + const start = parseInt(parts[0], 10); + let end = parts[1] ? parseInt(parts[1], 10) : size - 1; + if (end > size) { + end = size - 1; + } + const chunksize = end - start + 1; + + return { + stream: fs.createReadStream(path, { start, end }), + start, + end, + chunksize, + }; +} + +/** + * ストリームにcleanupハンドラを設定する + * ストリームでない場合は即座にcleanupを実行する + */ +export function attachStreamCleanup(data: IImageStreamable['data'], cleanup: () => void): void { + if ('pipe' in data && typeof data.pipe === 'function') { + data.on('end', cleanup); + data.on('close', cleanup); + } else { + cleanup(); + } +} + +/** + * MIME タイプがブラウザセーフかどうかに応じて Content-Type を返す + */ +export function getSafeContentType(mime: string): string { + return FILE_TYPE_BROWSERSAFE.includes(mime) ? mime : 'application/octet-stream'; +} + +/** + * Range リクエストを処理してストリームを返す + * Range ヘッダーがない場合は通常のストリームを返す + */ +export function handleRangeRequest( + reply: FastifyReply, + rangeHeader: string | undefined, + size: number, + path: string, +): fs.ReadStream { + if (rangeHeader && size > 0) { + const { stream, start, end, chunksize } = createRangeStream(rangeHeader, size, path); + reply.header('Content-Range', `bytes ${start}-${end}/${size}`); + reply.header('Accept-Ranges', 'bytes'); + reply.header('Content-Length', chunksize); + reply.code(206); + return stream; + } + return fs.createReadStream(path); +} + +export type FileResponseOptions = { + mime: string; + filename: string; + size?: number; + cacheControl?: string; +}; + +/** + * ファイルレスポンス用の共通ヘッダーを設定する + */ +export function setFileResponseHeaders( + reply: FastifyReply, + options: FileResponseOptions, +): void { + reply.header('Content-Type', getSafeContentType(options.mime)); + reply.header('Cache-Control', options.cacheControl ?? 'max-age=31536000, immutable'); + reply.header('Content-Disposition', contentDisposition('inline', options.filename)); + if (options.size !== undefined) { + reply.header('Content-Length', options.size); + } +} + +/** + * cleanup が必要なファイルかどうかを判定する型ガード + */ +export function needsCleanup void }>(file: T): file is T & { cleanup: () => void } { + return 'cleanup' in file && typeof file.cleanup === 'function'; +} diff --git a/packages/backend/src/server/oauth/OAuth2ProviderService.ts b/packages/backend/src/server/oauth/OAuth2ProviderService.ts index d2391c43ab..840c34b806 100644 --- a/packages/backend/src/server/oauth/OAuth2ProviderService.ts +++ b/packages/backend/src/server/oauth/OAuth2ProviderService.ts @@ -123,41 +123,86 @@ function parseMicroformats(doc: htmlParser.HTMLElement, baseUrl: string, id: str return { name, logo }; } -// https://indieauth.spec.indieweb.org/#client-information-discovery -// "Authorization servers SHOULD support parsing the [h-app] Microformat from the client_id, -// and if there is an [h-app] with a url property matching the client_id URL, -// then it should use the name and icon and display them on the authorization prompt." -// (But we don't display any icon for now) -// https://indieauth.spec.indieweb.org/#redirect-url -// "The client SHOULD publish one or more tags or Link HTTP headers with a rel attribute -// of redirect_uri at the client_id URL. -// Authorization endpoints verifying that a redirect_uri is allowed for use by a client MUST -// look for an exact match of the given redirect_uri in the request against the list of -// redirect_uris discovered after resolving any relative URLs." async function discoverClientInformation(logger: Logger, httpRequestService: HttpRequestService, id: string): Promise { try { const res = await httpRequestService.send(id); - const redirectUris: string[] = []; + const redirectUris: string[] = []; + let name = id; + let logo: string | null = null; + + // https://indieauth.spec.indieweb.org/#redirect-url + // "The client SHOULD publish one or more tags or Link HTTP headers with a rel attribute + // of redirect_uri at the client_id URL. + // Authorization endpoints verifying that a redirect_uri is allowed for use by a client MUST + // look for an exact match of the given redirect_uri in the request against the list of + // redirect_uris discovered after resolving any relative URLs." const linkHeader = res.headers.get('link'); if (linkHeader) { redirectUris.push(...httpLinkHeader.parse(linkHeader).get('rel', 'redirect_uri').map(r => r.uri)); } - const text = await res.text(); - const doc = htmlParser.parse(`

${text}
`); + const contentType = res.headers.get('content-type'); + const mediaType = contentType ? contentType.split(';')[0].trim() : null; + if (mediaType === 'application/json') { + // Client discovery via JSON document (11 July 2024 spec) + // https://indieauth.spec.indieweb.org/#client-metadata + // "Clients SHOULD have a JSON [RFC7159] document at their client_id URL containing + // client metadata defined in [RFC7591], the minimum properties for an IndieAuth + // client defined below." - redirectUris.push(...[...doc.querySelectorAll('link[rel=redirect_uri][href]')].map(el => el.attributes.href)); + const json = await res.json() as { + client_id: string; + client_name?: string; + client_uri: string; + logo_uri?: string; + redirect_uris?: string[]; + }; - let name = id; - let logo: string | null = null; - if (text) { - const microformats = parseMicroformats(doc, res.url, id); - if (typeof microformats.name === 'string') { - name = microformats.name; + // https://indieauth.spec.indieweb.org/#client-metadata-li-1 + // "The authorization server MUST verify that the client_id in the document matches the + // client_id of the URL where the document was retrieved." + if (json.client_id !== id) { + throw new AuthorizationError('client_id in the document does not match the client_id URL', 'invalid_request'); } - if (typeof microformats.logo === 'string') { - logo = microformats.logo; + + // https://indieauth.spec.indieweb.org/#client-metadata-li-1 + // "The client_uri MUST be a prefix of the client_id." + if (!json.client_uri || !id.startsWith(json.client_uri)) { + throw new AuthorizationError('client_uri is not a prefix of client_id', 'invalid_request'); + } + + if (typeof json.client_name === 'string') { + name = json.client_name; + } + + if (typeof json.logo_uri === 'string') { + // Since uri can be relative, resolve it against the document URL + logo = new URL(json.logo_uri, res.url).toString(); + } + + if (Array.isArray(json.redirect_uris)) { + redirectUris.push(...json.redirect_uris.filter((uri): uri is string => typeof uri === 'string')); + } + } else { + // Client discovery via HTML microformats (12 February 2022 spec) + // https://indieauth.spec.indieweb.org/20220212/#client-information-discovery + // "Authorization servers SHOULD support parsing the [h-app] Microformat from the client_id, + // and if there is an [h-app] with a url property matching the client_id URL, + // then it should use the name and icon and display them on the authorization prompt." + const text = await res.text(); + const doc = htmlParser.parse(`
${text}
`); + + redirectUris.push(...[...doc.querySelectorAll('link[rel=redirect_uri][href]')].map(el => el.attributes.href)); + + if (text) { + const microformats = parseMicroformats(doc, res.url, id); + if (typeof microformats.name === 'string') { + name = microformats.name; + } + if (typeof microformats.logo === 'string') { + logo = microformats.logo; + } } } @@ -172,6 +217,8 @@ async function discoverClientInformation(logger: Logger, httpRequestService: Htt logger.error('Error while fetching client information', { err }); if (err instanceof StatusError) { throw new AuthorizationError('Failed to fetch client information', 'invalid_request'); + } else if (err instanceof AuthorizationError) { + throw err; } else { throw new AuthorizationError('Failed to parse client information', 'server_error'); } diff --git a/packages/backend/src/server/web/ClientServerService.ts b/packages/backend/src/server/web/ClientServerService.ts index bcea935409..24bc619e79 100644 --- a/packages/backend/src/server/web/ClientServerService.ts +++ b/packages/backend/src/server/web/ClientServerService.ts @@ -4,8 +4,9 @@ */ import { randomUUID } from 'node:crypto'; -import { dirname } from 'node:path'; +import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import * as fs from 'node:fs'; import { Inject, Injectable } from '@nestjs/common'; import ms from 'ms'; import sharp from 'sharp'; @@ -69,13 +70,28 @@ import type { FastifyError, FastifyInstance, FastifyPluginOptions, FastifyReply const _filename = fileURLToPath(import.meta.url); const _dirname = dirname(_filename); -const staticAssets = `${_dirname}/../../../assets/`; -const clientAssets = `${_dirname}/../../../../frontend/assets/`; -const assets = `${_dirname}/../../../../../built/_frontend_dist_/`; -const swAssets = `${_dirname}/../../../../../built/_sw_dist_/`; -const frontendViteOut = `${_dirname}/../../../../../built/_frontend_vite_/`; -const frontendEmbedViteOut = `${_dirname}/../../../../../built/_frontend_embed_vite_/`; -const tarball = `${_dirname}/../../../../../built/tarball/`; +let rootDir = _dirname; +// 見つかるまで上に遡る +while (!fs.existsSync(resolve(rootDir, 'packages'))) { + const parentDir = dirname(rootDir); + if (parentDir === rootDir) { + throw new Error('Cannot find root directory'); + } + rootDir = parentDir; +} + +const backendRootDir = resolve(rootDir, 'packages/backend'); +const frontendRootDir = resolve(rootDir, 'packages/frontend'); + +const staticAssets = resolve(backendRootDir, 'assets'); +const clientAssets = resolve(frontendRootDir, 'assets'); +const assets = resolve(rootDir, 'built/_frontend_dist_'); +const swAssets = resolve(rootDir, 'built/_sw_dist_'); +const fluentEmojisDir = resolve(rootDir, 'fluent-emojis/dist'); +const twemojiDir = resolve(backendRootDir, 'node_modules/@discordapp/twemoji/dist/svg'); +const frontendViteOut = resolve(rootDir, 'built/_frontend_vite_'); +const frontendEmbedViteOut = resolve(rootDir, 'built/_frontend_embed_vite_'); +const tarball = resolve(rootDir, 'built/tarball'); @Injectable() export class ClientServerService { @@ -207,6 +223,7 @@ export class ClientServerService { //#region vite assets if (this.config.frontendEmbedManifestExists) { + console.log(`[ClientServerService] Using built frontend vite assets. ${frontendViteOut}`); fastify.register((fastify, options, done) => { fastify.register(fastifyStatic, { root: frontendViteOut, @@ -226,6 +243,7 @@ export class ClientServerService { done(); }); } else { + console.log('[ClientServerService] Proxying to Vite dev server.'); const urlOriginWithoutPort = configUrl.origin.replace(/:\d+$/, ''); const port = (process.env.VITE_PORT ?? '5173'); @@ -297,7 +315,7 @@ export class ClientServerService { reply.header('Content-Security-Policy', 'default-src \'none\'; style-src \'unsafe-inline\''); - return await reply.sendFile(path, `${_dirname}/../../../../../fluent-emojis/dist/`, { + return reply.sendFile(path, fluentEmojisDir, { maxAge: ms('30 days'), }); }); @@ -312,7 +330,7 @@ export class ClientServerService { reply.header('Content-Security-Policy', 'default-src \'none\'; style-src \'unsafe-inline\''); - return await reply.sendFile(path, `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/`, { + return reply.sendFile(path, twemojiDir, { maxAge: ms('30 days'), }); }); @@ -326,7 +344,7 @@ export class ClientServerService { } const mask = await sharp( - `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/${path.replace('.png', '')}.svg`, + `${twemojiDir}/${path.replace('.png', '')}.svg`, { density: 1000 }, ) .resize(488, 488) @@ -854,9 +872,6 @@ export class ClientServerService { })); }); - const override = (source: string, target: string, depth = 0) => - [, ...target.split('/').filter(x => x), ...source.split('/').filter(x => x).splice(depth)].join('/'); - fastify.get('/flush', async (request, reply) => { let sendHeader = true; diff --git a/packages/backend/src/server/web/HtmlTemplateService.ts b/packages/backend/src/server/web/HtmlTemplateService.ts index 8ff985530d..36272c81d5 100644 --- a/packages/backend/src/server/web/HtmlTemplateService.ts +++ b/packages/backend/src/server/web/HtmlTemplateService.ts @@ -3,9 +3,9 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { dirname } from 'node:path'; +import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { promises as fsp } from 'node:fs'; +import { promises as fsp, existsSync } from 'node:fs'; import { languages } from 'i18n/const'; import { Injectable, Inject } from '@nestjs/common'; import { DI } from '@/di-symbols.js'; @@ -13,21 +13,34 @@ import { bindThis } from '@/decorators.js'; import { htmlSafeJsonStringify } from '@/misc/json-stringify-html-safe.js'; import { MetaEntityService } from '@/core/entities/MetaEntityService.js'; import type { FastifyReply } from 'fastify'; +import type { Manifest } from 'vite'; import type { Config } from '@/config.js'; import type { MiMeta } from '@/models/Meta.js'; -import type { CommonData } from './views/_.js'; +import type { CommonData, ViteFiles } from './views/_.js'; const _filename = fileURLToPath(import.meta.url); const _dirname = dirname(_filename); -const frontendVitePublic = `${_dirname}/../../../../frontend/public/`; -const frontendEmbedVitePublic = `${_dirname}/../../../../frontend-embed/public/`; +let rootDir = _dirname; +// 見つかるまで上に遡る +while (!existsSync(resolve(rootDir, 'packages'))) { + const parentDir = dirname(rootDir); + if (parentDir === rootDir) { + throw new Error('Cannot find root directory'); + } + rootDir = parentDir; +} + +const frontendViteBuilt = resolve(rootDir, 'built/_frontend_vite_'); +const frontendEmbedViteBuilt = resolve(rootDir, 'built/_frontend_embed_vite_'); @Injectable() export class HtmlTemplateService { - private frontendBootloadersFetched = false; + private frontendAssetsFetched = false; + public frontendViteFiles: ViteFiles | null = null; public frontendBootloaderJs: string | null = null; public frontendBootloaderCss: string | null = null; + public frontendEmbedViteFiles: ViteFiles | null = null; public frontendEmbedBootloaderJs: string | null = null; public frontendEmbedBootloaderCss: string | null = null; @@ -42,18 +55,92 @@ export class HtmlTemplateService { ) { } + // 初期ロードで読み込むべきファイルのパスを収集する。 + // See https://ja.vite.dev/guide/backend-integration @bindThis - private async prepareFrontendBootloaders() { - if (this.frontendBootloadersFetched) return; - this.frontendBootloadersFetched = true; + private collectViteAssetFiles(manifest: Manifest): ViteFiles { + const entryFile = Object.values(manifest).find((chunk) => chunk.isEntry); + if (!entryFile) return { + entryJs: null, + css: [], + modulePreloads: [], + }; - const [bootJs, bootCss, embedBootJs, embedBootCss] = await Promise.all([ - fsp.readFile(`${frontendVitePublic}loader/boot.js`, 'utf-8').catch(() => null), - fsp.readFile(`${frontendVitePublic}loader/style.css`, 'utf-8').catch(() => null), - fsp.readFile(`${frontendEmbedVitePublic}loader/boot.js`, 'utf-8').catch(() => null), - fsp.readFile(`${frontendEmbedVitePublic}loader/style.css`, 'utf-8').catch(() => null), + const seenChunkIds = new Set(); + const cssFiles = new Set(); + const modulePreloads = new Set(); + + if (entryFile.css) { + entryFile.css.forEach((css) => cssFiles.add(css)); + } + + if (entryFile.imports != null && Array.isArray(entryFile.imports)) { + function collectImports(imports: string[], recursive = false) { + for (const importId of imports) { + if (seenChunkIds.has(importId)) continue; + seenChunkIds.add(importId); + + const importedChunk = manifest[importId]; + if (!importedChunk) return; + + if (importedChunk.css) { + importedChunk.css.forEach((css) => cssFiles.add(css)); + } + + if (importedChunk.imports != null && Array.isArray(importedChunk.imports)) { + collectImports(importedChunk.imports, true); + } + + if (!recursive) { + modulePreloads.add(importedChunk.file); + } + } + } + + collectImports(entryFile.imports); + } + + return { + entryJs: entryFile.file, + css: Array.from(cssFiles), + modulePreloads: Array.from(modulePreloads), + }; + } + + @bindThis + private async prepareFrontendAssets() { + if (this.frontendAssetsFetched) return; + this.frontendAssetsFetched = true; + + const [ + bootJs, + bootCss, + embedBootJs, + embedBootCss, + ] = await Promise.all([ + fsp.readFile(resolve(frontendViteBuilt, 'loader/boot.js'), 'utf-8').catch(() => null), + fsp.readFile(resolve(frontendViteBuilt, 'loader/style.css'), 'utf-8').catch(() => null), + fsp.readFile(resolve(frontendEmbedViteBuilt, 'loader/boot.js'), 'utf-8').catch(() => null), + fsp.readFile(resolve(frontendEmbedViteBuilt, 'loader/style.css'), 'utf-8').catch(() => null), ]); + let feViteManifest: Manifest | null = null; + let embedFeViteManifest: Manifest | null = null; + + if (this.config.frontendManifestExists) { + const manifestContent = await fsp.readFile(resolve(frontendViteBuilt, 'manifest.json'), 'utf-8').catch(() => null); + feViteManifest = manifestContent ? JSON.parse(manifestContent) : null; + } + + if (this.config.frontendEmbedManifestExists) { + const manifestContent = await fsp.readFile(resolve(frontendEmbedViteBuilt, 'manifest.json'), 'utf-8').catch(() => null); + embedFeViteManifest = manifestContent ? JSON.parse(manifestContent) : null; + } + + if (feViteManifest != null) { + this.frontendViteFiles = this.collectViteAssetFiles(feViteManifest); + } + if (bootJs != null) { this.frontendBootloaderJs = bootJs; } @@ -62,6 +149,10 @@ export class HtmlTemplateService { this.frontendBootloaderCss = bootCss; } + if (embedFeViteManifest != null) { + this.frontendEmbedViteFiles = this.collectViteAssetFiles(embedFeViteManifest); + } + if (embedBootJs != null) { this.frontendEmbedBootloaderJs = embedBootJs; } @@ -73,7 +164,7 @@ export class HtmlTemplateService { @bindThis public async getCommonData(): Promise { - await this.prepareFrontendBootloaders(); + await this.prepareFrontendAssets(); return { version: this.config.version, @@ -90,8 +181,10 @@ export class HtmlTemplateService { metaJson: htmlSafeJsonStringify(await this.metaEntityService.packDetailed(this.meta)), now: Date.now(), federationEnabled: this.meta.federation !== 'none', + frontendViteFiles: this.frontendViteFiles, frontendBootloaderJs: this.frontendBootloaderJs, frontendBootloaderCss: this.frontendBootloaderCss, + frontendEmbedViteFiles: this.frontendEmbedViteFiles, frontendEmbedBootloaderJs: this.frontendEmbedBootloaderJs, frontendEmbedBootloaderCss: this.frontendEmbedBootloaderCss, }; diff --git a/packages/backend/src/server/web/views/_.ts b/packages/backend/src/server/web/views/_.ts index ac7418f362..f9b290b13a 100644 --- a/packages/backend/src/server/web/views/_.ts +++ b/packages/backend/src/server/web/views/_.ts @@ -24,6 +24,12 @@ export type MinimumCommonData = { config: Config; }; +export type ViteFiles = { + entryJs: string | null; + css: string[]; + modulePreloads: string[]; +}; + export type CommonData = MinimumCommonData & { langs: string[]; instanceName: string; @@ -36,8 +42,10 @@ export type CommonData = MinimumCommonData & { instanceUrl: string; now: number; federationEnabled: boolean; + frontendViteFiles: ViteFiles | null; frontendBootloaderJs: string | null; frontendBootloaderCss: string | null; + frontendEmbedViteFiles: ViteFiles | null; frontendEmbedBootloaderJs: string | null; frontendEmbedBootloaderCss: string | null; metaJson?: string; diff --git a/packages/backend/src/server/web/views/base-embed.tsx b/packages/backend/src/server/web/views/base-embed.tsx index 011b66592e..a656bb28a7 100644 --- a/packages/backend/src/server/web/views/base-embed.tsx +++ b/packages/backend/src/server/web/views/base-embed.tsx @@ -46,11 +46,11 @@ export function BaseEmbed(props: PropsWithChildren