Merge branch 'develop' into feat-12997

This commit is contained in:
kakkokari-gtyih 2024-03-22 21:09:53 +09:00
commit 155692b5ef
139 changed files with 2308 additions and 447 deletions

View File

@ -38,7 +38,7 @@
# Option 3: If neither of the above applies to you. # Option 3: If neither of the above applies to you.
# (In this case, the source code should be published # (In this case, the source code should be published
# on the Misskey interface. IT IS NOT ENOUGH TO # on the Misskey interface. IT IS NOT ENOUGH TO
# DISCLOSE THE SOURCE CODE WEHN A USER REQUESTS IT BY # DISCLOSE THE SOURCE CODE WHEN A USER REQUESTS IT BY
# E-MAIL OR OTHER MEANS. If you are not satisfied # E-MAIL OR OTHER MEANS. If you are not satisfied
# with this, it is recommended that you read the # with this, it is recommended that you read the
# license again carefully. Anyway, enabling this # license again carefully. Anyway, enabling this

View File

@ -19,7 +19,6 @@
"editorconfig.editorconfig", "editorconfig.editorconfig",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"Vue.volar", "Vue.volar",
"Vue.vscode-typescript-vue-plugin",
"Orta.vscode-jest", "Orta.vscode-jest",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"mrmlnc.vscode-json5" "mrmlnc.vscode-json5"

View File

@ -0,0 +1,75 @@
name: Check SPDX-License-Identifier
on:
push:
branches:
- master
- develop
pull_request:
jobs:
check-spdx-license-id:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4.1.1
- name: Check
run: |
counter=0
search() {
local directory="$1"
find "$directory" -type f \
'(' \
-name "*.cjs" -and -not -name '*.config.cjs' -o \
-name "*.html" -o \
-name "*.js" -and -not -name '*.config.js' -o \
-name "*.mjs" -and -not -name '*.config.mjs' -o \
-name "*.scss" -o \
-name "*.ts" -and -not -name '*.config.ts' -o \
-name "*.vue" \
')' -and \
-not -name '*eslint*'
}
check() {
local file="$1"
if ! (
grep -q "SPDX-FileCopyrightText: syuilo and misskey-project" "$file" ||
grep -q "SPDX-License-Identifier: AGPL-3.0-only" "$file"
); then
echo "Missing: $file"
((counter++))
fi
}
directories=(
"cypress/e2e"
"packages/backend/migration"
"packages/backend/src"
"packages/backend/test"
"packages/frontend/.storybook"
"packages/frontend/@types"
"packages/frontend/lib"
"packages/frontend/public"
"packages/frontend/src"
"packages/frontend/test"
"packages/misskey-bubble-game/src"
"packages/misskey-reversi/src"
"packages/sw/src"
"scripts"
)
for directory in "${directories[@]}"; do
for file in $(search $directory); do
check "$file"
done
done
if [ $counter -gt 0 ]; then
echo "SPDX-License-Identifier is missing in $counter files."
exit 1
else
echo "SPDX-License-Identifier is certainly described in all target files!"
exit 0
fi

View File

@ -3,9 +3,7 @@
"editorconfig.editorconfig", "editorconfig.editorconfig",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"Vue.volar", "Vue.volar",
"Vue.vscode-typescript-vue-plugin",
"Orta.vscode-jest", "Orta.vscode-jest",
"dbaeumer.vscode-eslint",
"mrmlnc.vscode-json5" "mrmlnc.vscode-json5"
] ]
} }

View File

@ -7,7 +7,7 @@
"*.test.ts": "typescript" "*.test.ts": "typescript"
}, },
"jest.jestCommandLine": "pnpm run jest", "jest.jestCommandLine": "pnpm run jest",
"jest.autoRun": "off", "jest.runMode": "on-demand",
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.fixAll": "explicit" "source.fixAll": "explicit"
}, },

View File

@ -1,14 +1,38 @@
## Unreleased ## Unreleased
### Note
- コントロールパネル内にあるサマリープロキシの設定個所がセキュリティから全般へ変更となります。
### General ### General
- - Enhance: URLプレビューの有効化・無効化を設定できるように #13569
- Enhance: アンテナでBotによるートを除外できるように
(Cherry-picked from https://github.com/MisskeyIO/misskey/pull/545)
- Fix: Play作成時に設定した公開範囲が機能していない問題を修正
### Client ### Client
- Enhance: 自分のノートの添付ファイルから直接ファイルの詳細ページに飛べるように - Enhance: 自分のノートの添付ファイルから直接ファイルの詳細ページに飛べるように
- Enhance: 広告がMisskeyと同一ドメインの場合はRouterで遷移するように
- Enhance: リアクション・いいねの総数を表示するように
- Enhance: リアクション受け入れが「いいねのみ」の場合はリアクション絵文字一覧を表示しないように
- Enhance: 設定>プラグインのページからプラグインの簡易的なログやエラーを見られるように
- 実装の都合により、プラグインは1つエラーを起こした時に即時停止するようになりました
- Enhance: ページのデザインを変更
- Enhance: 2要素認証ワンタイムパスワードの入力欄を改善
- Fix: 一部のページ内リンクが正しく動作しない問題を修正 - Fix: 一部のページ内リンクが正しく動作しない問題を修正
- Fix: 周年の実績が閏年を考慮しない問題を修正
- Fix: ローカルURLのプレビューポップアップが左上に表示される
- Fix: WebGL2をサポートしないブラウザで「季節に応じた画面の演出」が有効になっているとき、Misskeyが起動できなくなる問題を修正
(Cherry-picked from https://activitypub.software/TransFem-org/Sharkey/-/merge_requests/459)
- Fix: ページタイトルでローカルユーザーとリモートユーザーの区別がつかない問題を修正
(Cherry-picked from https://github.com/MisskeyIO/misskey/pull/528)
- Fix: コードブロックのシンタックスハイライトで使用される定義ファイルをCDNから取得するように #13177
- CDNから取得せずMisskey本体にバンドルする場合は`pacakges/frontend/vite.config.ts`を修正してください。
### Server ### Server
- - Enhance: エンドポイント`antennas/update`の必須項目を`antennaId`のみに
- Enhance: misskey-dev/summaly@5.1.0の取り込み(プレビュー生成処理の効率化)
- Fix: フォローリクエストを作成する際に既存のものは削除するように
(Cherry-picked from https://activitypub.software/TransFem-org/Sharkey/-/merge_requests/440)
## 2024.3.1 ## 2024.3.1

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
describe('Before setup instance', () => { describe('Before setup instance', () => {
beforeEach(() => { beforeEach(() => {
cy.resetState(); cy.resetState();

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
describe('Router transition', () => { describe('Router transition', () => {
describe('Redirect', () => { describe('Redirect', () => {
// サーバの初期化。ルートのテストに関しては各describeごとに1度だけ実行で十分だと思う使いまわした方が早い // サーバの初期化。ルートのテストに関しては各describeごとに1度だけ実行で十分だと思う使いまわした方が早い

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
/* flaky /* flaky
describe('After user signed in', () => { describe('After user signed in', () => {
beforeEach(() => { beforeEach(() => {

View File

@ -30,7 +30,7 @@ Cypress.Commands.add('visitHome', () => {
}) })
Cypress.Commands.add('resetState', () => { Cypress.Commands.add('resetState', () => {
cy.window(win => { cy.window().then(win => {
win.indexedDB.deleteDatabase('keyval-store'); win.indexedDB.deleteDatabase('keyval-store');
}); });
cy.request('POST', '/api/reset-db', {}).as('reset'); cy.request('POST', '/api/reset-db', {}).as('reset');

19
cypress/support/index.ts Normal file
View File

@ -0,0 +1,19 @@
declare global {
namespace Cypress {
interface Chainable {
login(username: string, password: string): Chainable<void>;
registerUser(
username: string,
password: string,
isAdmin?: boolean
): Chainable<void>;
resetState(): Chainable<void>;
visitHome(): Chainable<void>;
}
}
}
export {}

8
cypress/tsconfig.json Normal file
View File

@ -0,0 +1,8 @@
{
"compilerOptions": {
"lib": ["dom", "es5"],
"target": "es5",
"types": ["cypress", "node"]
},
"include": ["./**/*.ts"]
}

86
locales/index.d.ts vendored
View File

@ -1616,6 +1616,10 @@ export interface Locale extends ILocale {
* *
*/ */
"antennaExcludeKeywords": string; "antennaExcludeKeywords": string;
/**
* Botアカウントを除外
*/
"antennaExcludeBots": string;
/** /**
* AND指定になりOR指定になります * AND指定になりOR指定になります
*/ */
@ -1992,6 +1996,10 @@ export interface Locale extends ILocale {
* *
*/ */
"showNoteActionsOnlyHover": string; "showNoteActionsOnlyHover": string;
/**
*
*/
"showReactionsCount": string;
/** /**
* *
*/ */
@ -4908,6 +4916,18 @@ export interface Locale extends ILocale {
* *
*/ */
"gameRetry": string; "gameRetry": string;
/**
* 使
*/
"notUsePleaseLeaveBlank": string;
/**
* 使
*/
"useTotp": string;
/**
* 使
*/
"useBackupCode": string;
/** /**
* *
*/ */
@ -6842,6 +6862,10 @@ export interface Locale extends ILocale {
* *
*/ */
"viewSource": string; "viewSource": string;
/**
*
*/
"viewLog": string;
}; };
"_preferencesBackups": { "_preferencesBackups": {
/** /**
@ -8668,6 +8692,10 @@ export interface Locale extends ILocale {
* *
*/ */
"summary": string; "summary": string;
/**
* URLを知っている人は引き続きアクセスできます
*/
"visibilityDescription": string;
}; };
"_pages": { "_pages": {
/** /**
@ -8950,6 +8978,10 @@ export interface Locale extends ILocale {
* {n} * {n}
*/ */
"reactedBySomeUsers": ParameterizedString<"n">; "reactedBySomeUsers": ParameterizedString<"n">;
/**
* {n}
*/
"likedBySomeUsers": ParameterizedString<"n">;
/** /**
* {n} * {n}
*/ */
@ -9789,6 +9821,60 @@ export interface Locale extends ILocale {
*/ */
"header": string; "header": string;
}; };
"_urlPreviewSetting": {
/**
* URLプレビューの設定
*/
"title": string;
/**
* URLプレビューを有効にする
*/
"enable": string;
/**
* (ms)
*/
"timeout": string;
/**
*
*/
"timeoutDescription": string;
/**
* Content-Lengthの最大値(byte)
*/
"maximumContentLength": string;
/**
* Content-Lengthがこの値を超えた場合
*/
"maximumContentLengthDescription": string;
/**
* Content-Lengthが取得できた場合のみプレビューを生成
*/
"requireContentLength": string;
/**
* Content-Lengthを返さない場合
*/
"requireContentLengthDescription": string;
/**
* User-Agent
*/
"userAgent": string;
/**
* 使User-Agentを設定しますUser-Agentが使用されます
*/
"userAgentDescription": string;
/**
*
*/
"summaryProxy": string;
/**
* Misskey本体ではなく使
*/
"summaryProxyDescription": string;
/**
*
*/
"summaryProxyDescription2": string;
};
} }
declare const locales: { declare const locales: {
[lang: string]: Locale; [lang: string]: Locale;

View File

@ -400,6 +400,7 @@ name: "名前"
antennaSource: "受信ソース" antennaSource: "受信ソース"
antennaKeywords: "受信キーワード" antennaKeywords: "受信キーワード"
antennaExcludeKeywords: "除外キーワード" antennaExcludeKeywords: "除外キーワード"
antennaExcludeBots: "Botアカウントを除外"
antennaKeywordsDescription: "スペースで区切るとAND指定になり、改行で区切るとOR指定になります" antennaKeywordsDescription: "スペースで区切るとAND指定になり、改行で区切るとOR指定になります"
notifyAntenna: "新しいノートを通知する" notifyAntenna: "新しいノートを通知する"
withFileAntenna: "ファイルが添付されたノートのみ" withFileAntenna: "ファイルが添付されたノートのみ"
@ -494,6 +495,7 @@ emojiStyle: "絵文字のスタイル"
native: "ネイティブ" native: "ネイティブ"
disableDrawer: "メニューをドロワーで表示しない" disableDrawer: "メニューをドロワーで表示しない"
showNoteActionsOnlyHover: "ノートのアクションをホバー時のみ表示する" showNoteActionsOnlyHover: "ノートのアクションをホバー時のみ表示する"
showReactionsCount: "ノートのリアクション数を表示する"
noHistory: "履歴はありません" noHistory: "履歴はありません"
signinHistory: "ログイン履歴" signinHistory: "ログイン履歴"
enableAdvancedMfm: "高度なMFMを有効にする" enableAdvancedMfm: "高度なMFMを有効にする"
@ -1223,6 +1225,9 @@ enableHorizontalSwipe: "スワイプしてタブを切り替える"
loading: "読み込み中" loading: "読み込み中"
surrender: "やめる" surrender: "やめる"
gameRetry: "リトライ" gameRetry: "リトライ"
notUsePleaseLeaveBlank: "使用しない場合は空欄にしてください"
useTotp: "ワンタイムパスワードを使う"
useBackupCode: "バックアップコードを使う"
prohibitSkippingInitialTutorial: "チュートリアルをスキップできないようにする" prohibitSkippingInitialTutorial: "チュートリアルをスキップできないようにする"
prohibitSkippingInitialTutorialDescription: "新規登録したユーザーに表示されるチュートリアルをスキップできないようにします。チュートリアルを完了しなかったりチュートリアルページを回避したりした場合でも、強制的にリダイレクトされます。" prohibitSkippingInitialTutorialDescription: "新規登録したユーザーに表示されるチュートリアルをスキップできないようにします。チュートリアルを完了しなかったりチュートリアルページを回避したりした場合でも、強制的にリダイレクトされます。"
@ -1782,6 +1787,7 @@ _plugin:
installWarn: "信頼できないプラグインはインストールしないでください。" installWarn: "信頼できないプラグインはインストールしないでください。"
manage: "プラグインの管理" manage: "プラグインの管理"
viewSource: "ソースを表示" viewSource: "ソースを表示"
viewLog: "ログを表示"
_preferencesBackups: _preferencesBackups:
list: "作成したバックアップ" list: "作成したバックアップ"
@ -2289,6 +2295,7 @@ _play:
title: "タイトル" title: "タイトル"
script: "スクリプト" script: "スクリプト"
summary: "説明" summary: "説明"
visibilityDescription: "非公開に設定するとプロフィールに表示されなくなりますが、URLを知っている人は引き続きアクセスできます。"
_pages: _pages:
newPage: "ページの作成" newPage: "ページの作成"
@ -2366,6 +2373,7 @@ _notification:
sendTestNotification: "テスト通知を送信する" sendTestNotification: "テスト通知を送信する"
notificationWillBeDisplayedLikeThis: "通知はこのように表示されます" notificationWillBeDisplayedLikeThis: "通知はこのように表示されます"
reactedBySomeUsers: "{n}人がリアクションしました" reactedBySomeUsers: "{n}人がリアクションしました"
likedBySomeUsers: "{n}人がいいねしました"
renotedBySomeUsers: "{n}人がリノートしました" renotedBySomeUsers: "{n}人がリノートしました"
followedBySomeUsers: "{n}人にフォローされました" followedBySomeUsers: "{n}人にフォローされました"
flushNotification: "通知の履歴をリセットする" flushNotification: "通知の履歴をリセットする"
@ -2608,3 +2616,17 @@ _offlineScreen:
title: "オフライン - サーバーに接続できません" title: "オフライン - サーバーに接続できません"
header: "サーバーに接続できません" header: "サーバーに接続できません"
_urlPreviewSetting:
title: "URLプレビューの設定"
enable: "URLプレビューを有効にする"
timeout: "プレビュー取得時のタイムアウト(ms)"
timeoutDescription: "プレビュー取得の所要時間がこの値を超えた場合、プレビューは生成されません。"
maximumContentLength: "Content-Lengthの最大値(byte)"
maximumContentLengthDescription: "Content-Lengthがこの値を超えた場合、プレビューは生成されません。"
requireContentLength: "Content-Lengthが取得できた場合のみプレビューを生成"
requireContentLengthDescription: "相手サーバがContent-Lengthを返さない場合、プレビューは生成されません。"
userAgent: "User-Agent"
userAgentDescription: "プレビュー取得時に使用されるUser-Agentを設定します。空欄の場合、デフォルトのUser-Agentが使用されます。"
summaryProxy: "プレビューを生成するプロキシのエンドポイント"
summaryProxyDescription: "Misskey本体ではなく、サマリープロキシを使用してプレビューを生成します。"
summaryProxyDescription2: "プロキシには下記パラメータがクエリ文字列として連携されます。プロキシ側がこれらをサポートしない場合、設定値は無視されます。"

View File

@ -59,6 +59,7 @@
"typescript": "5.3.3" "typescript": "5.3.3"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^20.11.28",
"@typescript-eslint/eslint-plugin": "7.1.0", "@typescript-eslint/eslint-plugin": "7.1.0",
"@typescript-eslint/parser": "7.1.0", "@typescript-eslint/parser": "7.1.0",
"cross-env": "7.0.3", "cross-env": "7.0.3",

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { loadConfig } from './built/config.js' import { loadConfig } from './built/config.js'
import { genOpenapiSpec } from './built/server/api/openapi/gen-spec.js' import { genOpenapiSpec } from './built/server/api/openapi/gen-spec.js'
import { writeFileSync } from "node:fs"; import { writeFileSync } from "node:fs";
@ -5,4 +10,4 @@ import { writeFileSync } from "node:fs";
const config = loadConfig(); const config = loadConfig();
const spec = genOpenapiSpec(config, true); const spec = genOpenapiSpec(config, true);
writeFileSync('./built/api.json', JSON.stringify(spec), 'utf-8'); writeFileSync('./built/api.json', JSON.stringify(spec), 'utf-8');

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class UserBlacklistAnntena1689325027964 { export class UserBlacklistAnntena1689325027964 {
name = 'UserBlacklistAnntena1689325027964' name = 'UserBlacklistAnntena1689325027964'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class FixRenoteMuting1690417561185 { export class FixRenoteMuting1690417561185 {
name = 'FixRenoteMuting1690417561185' name = 'FixRenoteMuting1690417561185'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class ChangeCacheRemoteFilesDefault1690417561186 { export class ChangeCacheRemoteFilesDefault1690417561186 {
name = 'ChangeCacheRemoteFilesDefault1690417561186' name = 'ChangeCacheRemoteFilesDefault1690417561186'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class Fix1690417561187 { export class Fix1690417561187 {
name = 'Fix1690417561187' name = 'Fix1690417561187'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class User2faBackupCodes1690569881926 { export class User2faBackupCodes1690569881926 {
name = 'User2faBackupCodes1690569881926' name = 'User2faBackupCodes1690569881926'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class RefineAnnouncement1691649257651 { export class RefineAnnouncement1691649257651 {
name = 'RefineAnnouncement1691649257651' name = 'RefineAnnouncement1691649257651'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class RefineAnnouncement21691657412740 { export class RefineAnnouncement21691657412740 {
name = 'RefineAnnouncement21691657412740' name = 'RefineAnnouncement21691657412740'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class VerifiedLinks1695260774117 { export class VerifiedLinks1695260774117 {
name = 'VerifiedLinks1695260774117' name = 'VerifiedLinks1695260774117'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class FollowingNotify1695288787870 { export class FollowingNotify1695288787870 {
name = 'FollowingNotify1695288787870' name = 'FollowingNotify1695288787870'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class ShortName1695440131671 { export class ShortName1695440131671 {
name = 'ShortName1695440131671' name = 'ShortName1695440131671'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class MutingNotificationTypes1695605508898 { export class MutingNotificationTypes1695605508898 {
name = 'MutingNotificationTypes1695605508898' name = 'MutingNotificationTypes1695605508898'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class NoteUpdatedAt1695901659683 { export class NoteUpdatedAt1695901659683 {
name = 'NoteUpdatedAt1695901659683' name = 'NoteUpdatedAt1695901659683'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class UserListMembership1696323464251 { export class UserListMembership1696323464251 {
name = 'UserListMembership1696323464251' name = 'UserListMembership1696323464251'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class Hibernation1696331570827 { export class Hibernation1696331570827 {
name = 'Hibernation1696331570827' name = 'Hibernation1696331570827'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class Clean1696332072038 { export class Clean1696332072038 {
name = 'Clean1696332072038' name = 'Clean1696332072038'

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class HardMute1700383825690 { export class HardMute1700383825690 {
name = 'HardMute1700383825690' name = 'HardMute1700383825690'

View File

@ -0,0 +1,42 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class UrlPreviewMeta1710512074000 {
name = 'UrlPreviewMeta1710512074000'
async up(queryRunner) {
await queryRunner.query(`
alter table meta
rename column "summalyProxy" to "urlPreviewSummaryProxyUrl";
alter table meta
add "urlPreviewEnabled" boolean default true not null;
alter table meta
add "urlPreviewTimeout" integer default 10000 not null;
alter table meta
add "urlPreviewMaximumContentLength" bigint default 10485760 not null;
alter table meta
add "urlPreviewRequireContentLength" boolean default false not null;
alter table meta
add "urlPreviewUserAgent" varchar(1024) default null;
`);
}
async down(queryRunner) {
await queryRunner.query(`
alter table meta
rename column "urlPreviewSummaryProxyUrl" to "summalyProxy";
alter table meta
drop column "urlPreviewEnabled";
alter table meta
drop column "urlPreviewTimeout";
alter table meta
drop column "urlPreviewMaximumContentLength";
alter table meta
drop column "urlPreviewRequireContentLength";
alter table meta
drop column "urlPreviewUserAgent";
`);
}
}

View File

@ -0,0 +1,16 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export class AntennaExcludeBots1710919614510 {
name = 'AntennaExcludeBots1710919614510'
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "antenna" ADD "excludeBots" boolean NOT NULL DEFAULT false`);
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "antenna" DROP COLUMN "excludeBots"`);
}
}

View File

@ -19,7 +19,7 @@
"watch": "node watch.mjs", "watch": "node watch.mjs",
"restart": "pnpm build && pnpm start", "restart": "pnpm build && pnpm start",
"dev": "nodemon -w src -e ts,js,mjs,cjs,json --exec \"cross-env NODE_ENV=development pnpm run restart\"", "dev": "nodemon -w src -e ts,js,mjs,cjs,json --exec \"cross-env NODE_ENV=development pnpm run restart\"",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit && tsc -p test --noEmit",
"eslint": "eslint --quiet \"src/**/*.ts\"", "eslint": "eslint --quiet \"src/**/*.ts\"",
"lint": "pnpm typecheck && pnpm eslint", "lint": "pnpm typecheck && pnpm eslint",
"jest": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --forceExit --config jest.config.unit.cjs", "jest": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --forceExit --config jest.config.unit.cjs",
@ -80,7 +80,7 @@
"@fastify/static": "6.12.0", "@fastify/static": "6.12.0",
"@fastify/view": "8.2.0", "@fastify/view": "8.2.0",
"@misskey-dev/sharp-read-bmp": "1.2.0", "@misskey-dev/sharp-read-bmp": "1.2.0",
"@misskey-dev/summaly": "5.0.3", "@misskey-dev/summaly": "5.1.0",
"@nestjs/common": "10.3.3", "@nestjs/common": "10.3.3",
"@nestjs/core": "10.3.3", "@nestjs/core": "10.3.3",
"@nestjs/testing": "10.3.3", "@nestjs/testing": "10.3.3",

View File

@ -92,7 +92,7 @@ export class AntennaService implements OnApplicationShutdown {
} }
@bindThis @bindThis
public async addNoteToAntennas(note: MiNote, noteUser: { id: MiUser['id']; username: string; host: string | null; }): Promise<void> { public async addNoteToAntennas(note: MiNote, noteUser: { id: MiUser['id']; username: string; host: string | null; isBot: boolean; }): Promise<void> {
const antennas = await this.getAntennas(); const antennas = await this.getAntennas();
const antennasWithMatchResult = await Promise.all(antennas.map(antenna => this.checkHitAntenna(antenna, note, noteUser).then(hit => [antenna, hit] as const))); const antennasWithMatchResult = await Promise.all(antennas.map(antenna => this.checkHitAntenna(antenna, note, noteUser).then(hit => [antenna, hit] as const)));
const matchedAntennas = antennasWithMatchResult.filter(([, hit]) => hit).map(([antenna]) => antenna); const matchedAntennas = antennasWithMatchResult.filter(([, hit]) => hit).map(([antenna]) => antenna);
@ -110,10 +110,12 @@ export class AntennaService implements OnApplicationShutdown {
// NOTE: フォローしているユーザーのノート、リストのユーザーのノート、グループのユーザーのノート指定はパフォーマンス上の理由で無効になっている // NOTE: フォローしているユーザーのノート、リストのユーザーのノート、グループのユーザーのノート指定はパフォーマンス上の理由で無効になっている
@bindThis @bindThis
public async checkHitAntenna(antenna: MiAntenna, note: (MiNote | Packed<'Note'>), noteUser: { id: MiUser['id']; username: string; host: string | null; }): Promise<boolean> { public async checkHitAntenna(antenna: MiAntenna, note: (MiNote | Packed<'Note'>), noteUser: { id: MiUser['id']; username: string; host: string | null; isBot: boolean; }): Promise<boolean> {
if (note.visibility === 'specified') return false; if (note.visibility === 'specified') return false;
if (note.visibility === 'followers') return false; if (note.visibility === 'followers') return false;
if (antenna.excludeBots && noteUser.isBot) return false;
if (antenna.localOnly && noteUser.host != null) return false; if (antenna.localOnly && noteUser.host != null) return false;
if (!antenna.withReplies && note.replyId != null) return false; if (!antenna.withReplies && note.replyId != null) return false;

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Inject, Injectable, OnModuleInit } from '@nestjs/common'; import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import Redis from 'ioredis'; import Redis from 'ioredis';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';

View File

@ -511,6 +511,12 @@ export class UserFollowingService implements OnModuleInit {
if (blocking) throw new Error('blocking'); if (blocking) throw new Error('blocking');
if (blocked) throw new Error('blocked'); if (blocked) throw new Error('blocked');
// Remove old follow requests before creating a new one.
await this.followRequestsRepository.delete({
followeeId: followee.id,
followerId: follower.id,
});
const followRequest = await this.followRequestsRepository.insert({ const followRequest = await this.followRequestsRepository.insert({
id: this.idService.gen(), id: this.idService.gen(),
followerId: follower.id, followerId: follower.id,

View File

@ -129,7 +129,7 @@ export class ApNoteService {
value, value,
object, object,
}); });
throw new Error('invalid note'); throw err;
} }
const note = object as IPost; const note = object as IPost;

View File

@ -459,13 +459,15 @@ export default abstract class Chart<T extends Schema> {
} }
} }
// bake unique count // bake cardinality
for (const [k, v] of Object.entries(finalDiffs)) { for (const [k, v] of Object.entries(finalDiffs)) {
if (this.schema[k].uniqueIncrement) { if (this.schema[k].uniqueIncrement) {
const name = COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof Columns<T>; const name = COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof Columns<T>;
const tempColumnName = UNIQUE_TEMP_COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof TempColumnsForUnique<T>; const tempColumnName = UNIQUE_TEMP_COLUMN_PREFIX + k.replaceAll('.', COLUMN_DELIMITER) as keyof TempColumnsForUnique<T>;
queryForHour[name] = new Set([...(v as string[]), ...(logHour[tempColumnName] as unknown as string[])]).size; const cardinalityOfHour = new Set([...(v as string[]), ...(logHour[tempColumnName] as unknown as string[])]).size;
queryForDay[name] = new Set([...(v as string[]), ...(logDay[tempColumnName] as unknown as string[])]).size; const cardinalityOfDay = new Set([...(v as string[]), ...(logDay[tempColumnName] as unknown as string[])]).size;
queryForHour[name] = cardinalityOfHour;
queryForDay[name] = cardinalityOfDay;
} }
} }
@ -637,7 +639,7 @@ export default abstract class Chart<T extends Schema> {
// 要求された範囲にログがひとつもなかったら // 要求された範囲にログがひとつもなかったら
if (logs.length === 0) { if (logs.length === 0) {
// もっとも新しいログを持ってくる // もっとも新しいログを持ってくる
// (すくなくともひとつログが無いと隙間埋めできないため) // (すくなくともひとつログが無いと補間できないため)
const recentLog = await repository.findOne({ const recentLog = await repository.findOne({
where: group ? { where: group ? {
group: group, group: group,
@ -654,7 +656,7 @@ export default abstract class Chart<T extends Schema> {
// 要求された範囲の最も古い箇所に位置するログが存在しなかったら // 要求された範囲の最も古い箇所に位置するログが存在しなかったら
} else if (!isTimeSame(new Date(logs.at(-1)!.date * 1000), gt)) { } else if (!isTimeSame(new Date(logs.at(-1)!.date * 1000), gt)) {
// 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する // 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する
// (隙間埋めできないため) // (補間できないため)
const outdatedLog = await repository.findOne({ const outdatedLog = await repository.findOne({
where: { where: {
date: LessThan(Chart.dateToTimestamp(gt)), date: LessThan(Chart.dateToTimestamp(gt)),
@ -683,7 +685,7 @@ export default abstract class Chart<T extends Schema> {
if (log) { if (log) {
chart.unshift(this.convertRawRecord(log)); chart.unshift(this.convertRawRecord(log));
} else { } else {
// 隙間埋め // 補間
const latest = logs.find(l => isTimeBefore(new Date(l.date * 1000), current)); const latest = logs.find(l => isTimeBefore(new Date(l.date * 1000), current));
const data = latest ? this.convertRawRecord(latest) : null; const data = latest ? this.convertRawRecord(latest) : null;
chart.unshift(this.getNewLog(data)); chart.unshift(this.getNewLog(data));

View File

@ -39,6 +39,7 @@ export class AntennaEntityService {
caseSensitive: antenna.caseSensitive, caseSensitive: antenna.caseSensitive,
localOnly: antenna.localOnly, localOnly: antenna.localOnly,
notify: antenna.notify, notify: antenna.notify,
excludeBots: antenna.excludeBots,
withReplies: antenna.withReplies, withReplies: antenna.withReplies,
withFile: antenna.withFile, withFile: antenna.withFile,
isActive: antenna.isActive, isActive: antenna.isActive,

View File

@ -112,6 +112,7 @@ export class MetaEntityService {
policies: { ...DEFAULT_POLICIES, ...instance.policies }, policies: { ...DEFAULT_POLICIES, ...instance.policies },
mediaProxy: this.config.mediaProxy, mediaProxy: this.config.mediaProxy,
enableUrlPreview: instance.urlPreviewEnabled,
}; };
return packed; return packed;

View File

@ -333,6 +333,7 @@ export class NoteEntityService implements OnModuleInit {
visibleUserIds: note.visibility === 'specified' ? note.visibleUserIds : undefined, visibleUserIds: note.visibility === 'specified' ? note.visibleUserIds : undefined,
renoteCount: note.renoteCount, renoteCount: note.renoteCount,
repliesCount: note.repliesCount, repliesCount: note.repliesCount,
reactionCount: Object.values(note.reactions).reduce((a, b) => a + b, 0),
reactions: this.reactionService.convertLegacyReactions(note.reactions), reactions: this.reactionService.convertLegacyReactions(note.reactions),
reactionEmojis: this.customEmojiService.populateEmojis(reactionEmojiNames, host), reactionEmojis: this.customEmojiService.populateEmojis(reactionEmojiNames, host),
reactionAndUserPairCache: opts.withReactionAndUserPairCache ? note.reactionAndUserPairCache : undefined, reactionAndUserPairCache: opts.withReactionAndUserPairCache ? note.reactionAndUserPairCache : undefined,

View File

@ -7,6 +7,7 @@ import { Inject, Injectable } from '@nestjs/common';
import * as Redis from 'ioredis'; import * as Redis from 'ioredis';
import _Ajv from 'ajv'; import _Ajv from 'ajv';
import { ModuleRef } from '@nestjs/core'; import { ModuleRef } from '@nestjs/core';
import { In } from 'typeorm';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import type { Config } from '@/config.js'; import type { Config } from '@/config.js';
import type { Packed } from '@/misc/json-schema.js'; import type { Packed } from '@/misc/json-schema.js';
@ -14,9 +15,30 @@ import type { Promiseable } from '@/misc/prelude/await-all.js';
import { awaitAll } from '@/misc/prelude/await-all.js'; import { awaitAll } from '@/misc/prelude/await-all.js';
import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from '@/const.js'; import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from '@/const.js';
import type { MiLocalUser, MiPartialLocalUser, MiPartialRemoteUser, MiRemoteUser, MiUser } from '@/models/User.js'; import type { MiLocalUser, MiPartialLocalUser, MiPartialRemoteUser, MiRemoteUser, MiUser } from '@/models/User.js';
import { birthdaySchema, descriptionSchema, localUsernameSchema, locationSchema, nameSchema, passwordSchema } from '@/models/User.js'; import {
import { MiNotification } from '@/models/Notification.js'; birthdaySchema,
import type { UsersRepository, UserSecurityKeysRepository, FollowingsRepository, FollowRequestsRepository, BlockingsRepository, MutingsRepository, DriveFilesRepository, NoteUnreadsRepository, UserNotePiningsRepository, UserProfilesRepository, AnnouncementReadsRepository, AnnouncementsRepository, MiUserProfile, RenoteMutingsRepository, UserMemoRepository } from '@/models/_.js'; descriptionSchema,
localUsernameSchema,
locationSchema,
nameSchema,
passwordSchema,
} from '@/models/User.js';
import type {
BlockingsRepository,
FollowingsRepository,
FollowRequestsRepository,
MiFollowing,
MiUserNotePining,
MiUserProfile,
MutingsRepository,
NoteUnreadsRepository,
RenoteMutingsRepository,
UserMemoRepository,
UserNotePiningsRepository,
UserProfilesRepository,
UserSecurityKeysRepository,
UsersRepository,
} from '@/models/_.js';
import { bindThis } from '@/decorators.js'; import { bindThis } from '@/decorators.js';
import { RoleService } from '@/core/RoleService.js'; import { RoleService } from '@/core/RoleService.js';
import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js'; import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js';
@ -46,11 +68,23 @@ function isRemoteUser(user: MiUser | { host: MiUser['host'] }): boolean {
return !isLocalUser(user); return !isLocalUser(user);
} }
export type UserRelation = {
id: MiUser['id']
following: MiFollowing | null,
isFollowing: boolean
isFollowed: boolean
hasPendingFollowRequestFromYou: boolean
hasPendingFollowRequestToYou: boolean
isBlocking: boolean
isBlocked: boolean
isMuted: boolean
isRenoteMuted: boolean
}
@Injectable() @Injectable()
export class UserEntityService implements OnModuleInit { export class UserEntityService implements OnModuleInit {
private apPersonService: ApPersonService; private apPersonService: ApPersonService;
private noteEntityService: NoteEntityService; private noteEntityService: NoteEntityService;
private driveFileEntityService: DriveFileEntityService;
private pageEntityService: PageEntityService; private pageEntityService: PageEntityService;
private customEmojiService: CustomEmojiService; private customEmojiService: CustomEmojiService;
private announcementService: AnnouncementService; private announcementService: AnnouncementService;
@ -89,9 +123,6 @@ export class UserEntityService implements OnModuleInit {
@Inject(DI.renoteMutingsRepository) @Inject(DI.renoteMutingsRepository)
private renoteMutingsRepository: RenoteMutingsRepository, private renoteMutingsRepository: RenoteMutingsRepository,
@Inject(DI.driveFilesRepository)
private driveFilesRepository: DriveFilesRepository,
@Inject(DI.noteUnreadsRepository) @Inject(DI.noteUnreadsRepository)
private noteUnreadsRepository: NoteUnreadsRepository, private noteUnreadsRepository: NoteUnreadsRepository,
@ -101,12 +132,6 @@ export class UserEntityService implements OnModuleInit {
@Inject(DI.userProfilesRepository) @Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository, private userProfilesRepository: UserProfilesRepository,
@Inject(DI.announcementReadsRepository)
private announcementReadsRepository: AnnouncementReadsRepository,
@Inject(DI.announcementsRepository)
private announcementsRepository: AnnouncementsRepository,
@Inject(DI.userMemosRepository) @Inject(DI.userMemosRepository)
private userMemosRepository: UserMemoRepository, private userMemosRepository: UserMemoRepository,
) { ) {
@ -115,7 +140,6 @@ export class UserEntityService implements OnModuleInit {
onModuleInit() { onModuleInit() {
this.apPersonService = this.moduleRef.get('ApPersonService'); this.apPersonService = this.moduleRef.get('ApPersonService');
this.noteEntityService = this.moduleRef.get('NoteEntityService'); this.noteEntityService = this.moduleRef.get('NoteEntityService');
this.driveFileEntityService = this.moduleRef.get('DriveFileEntityService');
this.pageEntityService = this.moduleRef.get('PageEntityService'); this.pageEntityService = this.moduleRef.get('PageEntityService');
this.customEmojiService = this.moduleRef.get('CustomEmojiService'); this.customEmojiService = this.moduleRef.get('CustomEmojiService');
this.announcementService = this.moduleRef.get('AnnouncementService'); this.announcementService = this.moduleRef.get('AnnouncementService');
@ -138,7 +162,7 @@ export class UserEntityService implements OnModuleInit {
public isRemoteUser = isRemoteUser; public isRemoteUser = isRemoteUser;
@bindThis @bindThis
public async getRelation(me: MiUser['id'], target: MiUser['id']) { public async getRelation(me: MiUser['id'], target: MiUser['id']): Promise<UserRelation> {
const [ const [
following, following,
isFollowed, isFollowed,
@ -211,6 +235,59 @@ export class UserEntityService implements OnModuleInit {
}; };
} }
@bindThis
public async getRelations(me: MiUser['id'], targets: MiUser['id'][]): Promise<Map<MiUser['id'], UserRelation>> {
const [
followers,
followees,
followersRequests,
followeesRequests,
blockers,
blockees,
muters,
renoteMuters,
] = await Promise.all([
this.followingsRepository.findBy({ followerId: me })
.then(f => new Map(f.map(it => [it.followeeId, it]))),
this.followingsRepository.findBy({ followeeId: me })
.then(it => it.map(it => it.followerId)),
this.followRequestsRepository.findBy({ followerId: me })
.then(it => it.map(it => it.followeeId)),
this.followRequestsRepository.findBy({ followeeId: me })
.then(it => it.map(it => it.followerId)),
this.blockingsRepository.findBy({ blockerId: me })
.then(it => it.map(it => it.blockeeId)),
this.blockingsRepository.findBy({ blockeeId: me })
.then(it => it.map(it => it.blockerId)),
this.mutingsRepository.findBy({ muterId: me })
.then(it => it.map(it => it.muteeId)),
this.renoteMutingsRepository.findBy({ muterId: me })
.then(it => it.map(it => it.muteeId)),
]);
return new Map(
targets.map(target => {
const following = followers.get(target) ?? null;
return [
target,
{
id: target,
following: following,
isFollowing: following != null,
isFollowed: followees.includes(target),
hasPendingFollowRequestFromYou: followersRequests.includes(target),
hasPendingFollowRequestToYou: followeesRequests.includes(target),
isBlocking: blockers.includes(target),
isBlocked: blockees.includes(target),
isMuted: muters.includes(target),
isRenoteMuted: renoteMuters.includes(target),
},
];
}),
);
}
@bindThis @bindThis
public async getHasUnreadAntenna(userId: MiUser['id']): Promise<boolean> { public async getHasUnreadAntenna(userId: MiUser['id']): Promise<boolean> {
/* /*
@ -303,6 +380,9 @@ export class UserEntityService implements OnModuleInit {
schema?: S, schema?: S,
includeSecrets?: boolean, includeSecrets?: boolean,
userProfile?: MiUserProfile, userProfile?: MiUserProfile,
userRelations?: Map<MiUser['id'], UserRelation>,
userMemos?: Map<MiUser['id'], string | null>,
pinNotes?: Map<MiUser['id'], MiUserNotePining[]>,
}, },
): Promise<Packed<S>> { ): Promise<Packed<S>> {
const opts = Object.assign({ const opts = Object.assign({
@ -317,13 +397,41 @@ export class UserEntityService implements OnModuleInit {
const isMe = meId === user.id; const isMe = meId === user.id;
const iAmModerator = me ? await this.roleService.isModerator(me as MiUser) : false; const iAmModerator = me ? await this.roleService.isModerator(me as MiUser) : false;
const relation = meId && !isMe && isDetailed ? await this.getRelation(meId, user.id) : null; const profile = isDetailed
const pins = isDetailed ? await this.userNotePiningsRepository.createQueryBuilder('pin') ? (opts.userProfile ?? await this.userProfilesRepository.findOneByOrFail({ userId: user.id }))
.where('pin.userId = :userId', { userId: user.id }) : null;
.innerJoinAndSelect('pin.note', 'note')
.orderBy('pin.id', 'DESC') let relation: UserRelation | null = null;
.getMany() : []; if (meId && !isMe && isDetailed) {
const profile = isDetailed ? (opts.userProfile ?? await this.userProfilesRepository.findOneByOrFail({ userId: user.id })) : null; if (opts.userRelations) {
relation = opts.userRelations.get(user.id) ?? null;
} else {
relation = await this.getRelation(meId, user.id);
}
}
let memo: string | null = null;
if (isDetailed && meId) {
if (opts.userMemos) {
memo = opts.userMemos.get(user.id) ?? null;
} else {
memo = await this.userMemosRepository.findOneBy({ userId: meId, targetUserId: user.id })
.then(row => row?.memo ?? null);
}
}
let pins: MiUserNotePining[] = [];
if (isDetailed) {
if (opts.pinNotes) {
pins = opts.pinNotes.get(user.id) ?? [];
} else {
pins = await this.userNotePiningsRepository.createQueryBuilder('pin')
.where('pin.userId = :userId', { userId: user.id })
.innerJoinAndSelect('pin.note', 'note')
.orderBy('pin.id', 'DESC')
.getMany();
}
}
const followingCount = profile == null ? null : const followingCount = profile == null ? null :
(profile.followingVisibility === 'public') || isMe ? user.followingCount : (profile.followingVisibility === 'public') || isMe ? user.followingCount :
@ -416,9 +524,7 @@ export class UserEntityService implements OnModuleInit {
twoFactorEnabled: profile!.twoFactorEnabled, twoFactorEnabled: profile!.twoFactorEnabled,
usePasswordLessLogin: profile!.usePasswordLessLogin, usePasswordLessLogin: profile!.usePasswordLessLogin,
securityKeys: profile!.twoFactorEnabled securityKeys: profile!.twoFactorEnabled
? this.userSecurityKeysRepository.countBy({ ? this.userSecurityKeysRepository.countBy({ userId: user.id }).then(result => result >= 1)
userId: user.id,
}).then(result => result >= 1)
: false, : false,
roles: this.roleService.getUserRoles(user.id).then(roles => roles.filter(role => role.isPublic).sort((a, b) => b.displayOrder - a.displayOrder).map(role => ({ roles: this.roleService.getUserRoles(user.id).then(roles => roles.filter(role => role.isPublic).sort((a, b) => b.displayOrder - a.displayOrder).map(role => ({
id: role.id, id: role.id,
@ -430,10 +536,7 @@ export class UserEntityService implements OnModuleInit {
isAdministrator: role.isAdministrator, isAdministrator: role.isAdministrator,
displayOrder: role.displayOrder, displayOrder: role.displayOrder,
}))), }))),
memo: meId == null ? null : await this.userMemosRepository.findOneBy({ memo: memo,
userId: meId,
targetUserId: user.id,
}).then(row => row?.memo ?? null),
moderationNote: iAmModerator ? (profile!.moderationNote ?? '') : undefined, moderationNote: iAmModerator ? (profile!.moderationNote ?? '') : undefined,
} : {}), } : {}),
@ -514,7 +617,7 @@ export class UserEntityService implements OnModuleInit {
return await awaitAll(packed); return await awaitAll(packed);
} }
public packMany<S extends 'MeDetailed' | 'UserDetailedNotMe' | 'UserDetailed' | 'UserLite' = 'UserLite'>( public async packMany<S extends 'MeDetailed' | 'UserDetailedNotMe' | 'UserDetailed' | 'UserLite' = 'UserLite'>(
users: (MiUser['id'] | MiUser)[], users: (MiUser['id'] | MiUser)[],
me?: { id: MiUser['id'] } | null | undefined, me?: { id: MiUser['id'] } | null | undefined,
options?: { options?: {
@ -522,6 +625,70 @@ export class UserEntityService implements OnModuleInit {
includeSecrets?: boolean, includeSecrets?: boolean,
}, },
): Promise<Packed<S>[]> { ): Promise<Packed<S>[]> {
return Promise.all(users.map(u => this.pack(u, me, options))); // -- IDのみの要素を補完して完全なエンティティ一覧を作る
const _users = users.filter((user): user is MiUser => typeof user !== 'string');
if (_users.length !== users.length) {
_users.push(
...await this.usersRepository.findBy({
id: In(users.filter((user): user is string => typeof user === 'string')),
}),
);
}
const _userIds = _users.map(u => u.id);
// -- 特に前提条件のない値群を取得
const profilesMap = await this.userProfilesRepository.findBy({ userId: In(_userIds) })
.then(profiles => new Map(profiles.map(p => [p.userId, p])));
// -- 実行者の有無や指定スキーマの種別によって要否が異なる値群を取得
let userRelations: Map<MiUser['id'], UserRelation> = new Map();
let userMemos: Map<MiUser['id'], string | null> = new Map();
let pinNotes: Map<MiUser['id'], MiUserNotePining[]> = new Map();
if (options?.schema !== 'UserLite') {
const meId = me ? me.id : null;
if (meId) {
userMemos = await this.userMemosRepository.findBy({ userId: meId })
.then(memos => new Map(memos.map(memo => [memo.targetUserId, memo.memo])));
if (_userIds.length > 0) {
userRelations = await this.getRelations(meId, _userIds);
pinNotes = await this.userNotePiningsRepository.createQueryBuilder('pin')
.where('pin.userId IN (:...userIds)', { userIds: _userIds })
.innerJoinAndSelect('pin.note', 'note')
.getMany()
.then(pinsNotes => {
const map = new Map<MiUser['id'], MiUserNotePining[]>();
for (const note of pinsNotes) {
const notes = map.get(note.userId) ?? [];
notes.push(note);
map.set(note.userId, notes);
}
for (const [, notes] of map.entries()) {
// pack側ではDESCで取得しているので、それに合わせて降順に並び替えておく
notes.sort((a, b) => b.id.localeCompare(a.id));
}
return map;
});
}
}
}
return Promise.all(
_users.map(u => this.pack(
u,
me,
{
...options,
userProfile: profilesMap.get(u.id),
userRelations: userRelations,
userMemos: userMemos,
pinNotes: pinNotes,
},
)),
);
} }
} }

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import type { onRequestHookHandler } from 'fastify'; import type { onRequestHookHandler } from 'fastify';
export const handleRequestRedirectToOmitSearch: onRequestHookHandler = (request, reply, done) => { export const handleRequestRedirectToOmitSearch: onRequestHookHandler = (request, reply, done) => {

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import type { MiNote } from '@/models/Note.js'; import type { MiNote } from '@/models/Note.js';
export function isPureRenote(note: MiNote): note is MiNote & { renoteId: NonNullable<MiNote['renoteId']> } { export function isPureRenote(note: MiNote): note is MiNote & { renoteId: NonNullable<MiNote['renoteId']> } {

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export type FetchFunction<K, V> = (key: K) => Promise<V>; export type FetchFunction<K, V> = (key: K) => Promise<V>;
type ResolveReject<V> = Parameters<ConstructorParameters<typeof Promise<V>>[0]>; type ResolveReject<V> = Parameters<ConstructorParameters<typeof Promise<V>>[0]>;

View File

@ -72,6 +72,11 @@ export class MiAntenna {
}) })
public caseSensitive: boolean; public caseSensitive: boolean;
@Column('boolean', {
default: false,
})
public excludeBots: boolean;
@Column('boolean', { @Column('boolean', {
default: false, default: false,
}) })

View File

@ -282,12 +282,6 @@ export class MiMeta {
}) })
public enableSensitiveMediaDetectionForVideos: boolean; public enableSensitiveMediaDetectionForVideos: boolean;
@Column('varchar', {
length: 1024,
nullable: true,
})
public summalyProxy: string | null;
@Column('boolean', { @Column('boolean', {
default: false, default: false,
}) })
@ -593,4 +587,36 @@ export class MiMeta {
default: 0, default: 0,
}) })
public notesPerOneAd: number; public notesPerOneAd: number;
@Column('boolean', {
default: true,
})
public urlPreviewEnabled: boolean;
@Column('integer', {
default: 10000,
})
public urlPreviewTimeout: number;
@Column('bigint', {
default: 1024 * 1024 * 10,
})
public urlPreviewMaximumContentLength: number;
@Column('boolean', {
default: true,
})
public urlPreviewRequireContentLength: boolean;
@Column('varchar', {
length: 1024,
nullable: true,
})
public urlPreviewSummaryProxyUrl: string | null;
@Column('varchar', {
length: 1024,
nullable: true,
})
public urlPreviewUserAgent: string | null;
} }

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { PrimaryColumn, Entity, Index, JoinColumn, Column, ManyToOne } from 'typeorm'; import { PrimaryColumn, Entity, Index, JoinColumn, Column, ManyToOne } from 'typeorm';
import { id } from './util/id.js'; import { id } from './util/id.js';
import { MiUser } from './User.js'; import { MiUser } from './User.js';

View File

@ -76,6 +76,11 @@ export const packedAntennaSchema = {
type: 'boolean', type: 'boolean',
optional: false, nullable: false, optional: false, nullable: false,
}, },
excludeBots: {
type: 'boolean',
optional: false, nullable: false,
default: false,
},
withReplies: { withReplies: {
type: 'boolean', type: 'boolean',
optional: false, nullable: false, optional: false, nullable: false,

View File

@ -211,6 +211,10 @@ export const packedMetaLiteSchema = {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: false,
}, },
enableUrlPreview: {
type: 'boolean',
optional: false, nullable: false,
},
backgroundImageUrl: { backgroundImageUrl: {
type: 'string', type: 'string',
optional: false, nullable: true, optional: false, nullable: true,

View File

@ -223,6 +223,10 @@ export const packedNoteSchema = {
}], }],
}, },
}, },
reactionCount: {
type: 'number',
optional: false, nullable: false,
},
renoteCount: { renoteCount: {
type: 'number', type: 'number',
optional: false, nullable: false, optional: false, nullable: false,

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export const packedSigninSchema = { export const packedSigninSchema = {
type: 'object', type: 'object',
properties: { properties: {

View File

@ -81,6 +81,7 @@ export class ExportAntennasProcessorService {
}) : null, }) : null,
caseSensitive: antenna.caseSensitive, caseSensitive: antenna.caseSensitive,
localOnly: antenna.localOnly, localOnly: antenna.localOnly,
excludeBots: antenna.excludeBots,
withReplies: antenna.withReplies, withReplies: antenna.withReplies,
withFile: antenna.withFile, withFile: antenna.withFile,
notify: antenna.notify, notify: antenna.notify,

View File

@ -44,6 +44,7 @@ const validate = new Ajv().compile({
} }, } },
caseSensitive: { type: 'boolean' }, caseSensitive: { type: 'boolean' },
localOnly: { type: 'boolean' }, localOnly: { type: 'boolean' },
excludeBots: { type: 'boolean' },
withReplies: { type: 'boolean' }, withReplies: { type: 'boolean' },
withFile: { type: 'boolean' }, withFile: { type: 'boolean' },
notify: { type: 'boolean' }, notify: { type: 'boolean' },
@ -88,6 +89,7 @@ export class ImportAntennasProcessorService {
users: (antenna.src === 'list' && antenna.userListAccts !== null ? antenna.userListAccts : antenna.users).filter(Boolean), users: (antenna.src === 'list' && antenna.userListAccts !== null ? antenna.userListAccts : antenna.users).filter(Boolean),
caseSensitive: antenna.caseSensitive, caseSensitive: antenna.caseSensitive,
localOnly: antenna.localOnly, localOnly: antenna.localOnly,
excludeBots: antenna.excludeBots,
withReplies: antenna.withReplies, withReplies: antenna.withReplies,
withFile: antenna.withFile, withFile: antenna.withFile,
notify: antenna.notify, notify: antenna.notify,

View File

@ -438,6 +438,8 @@ export const meta = {
summalyProxy: { summalyProxy: {
type: 'string', type: 'string',
optional: false, nullable: true, optional: false, nullable: true,
deprecated: true,
description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.',
}, },
themeColor: { themeColor: {
type: 'string', type: 'string',
@ -455,6 +457,30 @@ export const meta = {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: false,
}, },
urlPreviewEnabled: {
type: 'boolean',
optional: false, nullable: false,
},
urlPreviewTimeout: {
type: 'number',
optional: false, nullable: false,
},
urlPreviewMaximumContentLength: {
type: 'number',
optional: false, nullable: false,
},
urlPreviewRequireContentLength: {
type: 'boolean',
optional: false, nullable: false,
},
urlPreviewUserAgent: {
type: 'string',
optional: false, nullable: true,
},
urlPreviewSummaryProxyUrl: {
type: 'string',
optional: false, nullable: true,
},
}, },
}, },
} as const; } as const;
@ -538,7 +564,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
setSensitiveFlagAutomatically: instance.setSensitiveFlagAutomatically, setSensitiveFlagAutomatically: instance.setSensitiveFlagAutomatically,
enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos, enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos,
proxyAccountId: instance.proxyAccountId, proxyAccountId: instance.proxyAccountId,
summalyProxy: instance.summalyProxy,
email: instance.email, email: instance.email,
smtpSecure: instance.smtpSecure, smtpSecure: instance.smtpSecure,
smtpHost: instance.smtpHost, smtpHost: instance.smtpHost,
@ -582,6 +607,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
perUserHomeTimelineCacheMax: instance.perUserHomeTimelineCacheMax, perUserHomeTimelineCacheMax: instance.perUserHomeTimelineCacheMax,
perUserListTimelineCacheMax: instance.perUserListTimelineCacheMax, perUserListTimelineCacheMax: instance.perUserListTimelineCacheMax,
notesPerOneAd: instance.notesPerOneAd, notesPerOneAd: instance.notesPerOneAd,
summalyProxy: instance.urlPreviewSummaryProxyUrl,
urlPreviewEnabled: instance.urlPreviewEnabled,
urlPreviewTimeout: instance.urlPreviewTimeout,
urlPreviewMaximumContentLength: instance.urlPreviewMaximumContentLength,
urlPreviewRequireContentLength: instance.urlPreviewRequireContentLength,
urlPreviewUserAgent: instance.urlPreviewUserAgent,
urlPreviewSummaryProxyUrl: instance.urlPreviewSummaryProxyUrl,
}; };
}); });
} }

View File

@ -91,7 +91,6 @@ export const paramDef = {
type: 'string', type: 'string',
}, },
}, },
summalyProxy: { type: 'string', nullable: true },
deeplAuthKey: { type: 'string', nullable: true }, deeplAuthKey: { type: 'string', nullable: true },
deeplIsPro: { type: 'boolean' }, deeplIsPro: { type: 'boolean' },
enableEmail: { type: 'boolean' }, enableEmail: { type: 'boolean' },
@ -151,6 +150,16 @@ export const paramDef = {
type: 'string', type: 'string',
}, },
}, },
summalyProxy: {
type: 'string', nullable: true,
description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.',
},
urlPreviewEnabled: { type: 'boolean' },
urlPreviewTimeout: { type: 'integer' },
urlPreviewMaximumContentLength: { type: 'integer' },
urlPreviewRequireContentLength: { type: 'boolean' },
urlPreviewUserAgent: { type: 'string', nullable: true },
urlPreviewSummaryProxyUrl: { type: 'string', nullable: true },
}, },
required: [], required: [],
} as const; } as const;
@ -358,10 +367,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
set.langs = ps.langs.filter(Boolean); set.langs = ps.langs.filter(Boolean);
} }
if (ps.summalyProxy !== undefined) {
set.summalyProxy = ps.summalyProxy;
}
if (ps.enableEmail !== undefined) { if (ps.enableEmail !== undefined) {
set.enableEmail = ps.enableEmail; set.enableEmail = ps.enableEmail;
} }
@ -586,6 +591,32 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
set.bannedEmailDomains = ps.bannedEmailDomains; set.bannedEmailDomains = ps.bannedEmailDomains;
} }
if (ps.urlPreviewEnabled !== undefined) {
set.urlPreviewEnabled = ps.urlPreviewEnabled;
}
if (ps.urlPreviewTimeout !== undefined) {
set.urlPreviewTimeout = ps.urlPreviewTimeout;
}
if (ps.urlPreviewMaximumContentLength !== undefined) {
set.urlPreviewMaximumContentLength = ps.urlPreviewMaximumContentLength;
}
if (ps.urlPreviewRequireContentLength !== undefined) {
set.urlPreviewRequireContentLength = ps.urlPreviewRequireContentLength;
}
if (ps.urlPreviewUserAgent !== undefined) {
const value = (ps.urlPreviewUserAgent ?? '').trim();
set.urlPreviewUserAgent = value === '' ? null : ps.urlPreviewUserAgent;
}
if (ps.summalyProxy !== undefined || ps.urlPreviewSummaryProxyUrl !== undefined) {
const value = ((ps.urlPreviewSummaryProxyUrl ?? ps.summalyProxy) ?? '').trim();
set.urlPreviewSummaryProxyUrl = value === '' ? null : value;
}
const before = await this.metaService.fetch(true); const before = await this.metaService.fetch(true);
await this.metaService.update(set); await this.metaService.update(set);

View File

@ -64,6 +64,7 @@ export const paramDef = {
} }, } },
caseSensitive: { type: 'boolean' }, caseSensitive: { type: 'boolean' },
localOnly: { type: 'boolean' }, localOnly: { type: 'boolean' },
excludeBots: { type: 'boolean' },
withReplies: { type: 'boolean' }, withReplies: { type: 'boolean' },
withFile: { type: 'boolean' }, withFile: { type: 'boolean' },
notify: { type: 'boolean' }, notify: { type: 'boolean' },
@ -124,6 +125,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
users: ps.users, users: ps.users,
caseSensitive: ps.caseSensitive, caseSensitive: ps.caseSensitive,
localOnly: ps.localOnly, localOnly: ps.localOnly,
excludeBots: ps.excludeBots,
withReplies: ps.withReplies, withReplies: ps.withReplies,
withFile: ps.withFile, withFile: ps.withFile,
notify: ps.notify, notify: ps.notify,

View File

@ -63,11 +63,12 @@ export const paramDef = {
} }, } },
caseSensitive: { type: 'boolean' }, caseSensitive: { type: 'boolean' },
localOnly: { type: 'boolean' }, localOnly: { type: 'boolean' },
excludeBots: { type: 'boolean' },
withReplies: { type: 'boolean' }, withReplies: { type: 'boolean' },
withFile: { type: 'boolean' }, withFile: { type: 'boolean' },
notify: { type: 'boolean' }, notify: { type: 'boolean' },
}, },
required: ['antennaId', 'name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'], required: ['antennaId'],
} as const; } as const;
@Injectable() @Injectable()
@ -83,8 +84,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private globalEventService: GlobalEventService, private globalEventService: GlobalEventService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) { if (ps.keywords && ps.excludeKeywords) {
throw new Error('either keywords or excludeKeywords is required.'); if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) {
throw new Error('either keywords or excludeKeywords is required.');
}
} }
// Fetch the antenna // Fetch the antenna
const antenna = await this.antennasRepository.findOneBy({ const antenna = await this.antennasRepository.findOneBy({
@ -98,7 +101,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
let userList; let userList;
if (ps.src === 'list' && ps.userListId) { if ((ps.src === 'list' || antenna.src === 'list') && ps.userListId) {
userList = await this.userListsRepository.findOneBy({ userList = await this.userListsRepository.findOneBy({
id: ps.userListId, id: ps.userListId,
userId: me.id, userId: me.id,
@ -112,12 +115,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
await this.antennasRepository.update(antenna.id, { await this.antennasRepository.update(antenna.id, {
name: ps.name, name: ps.name,
src: ps.src, src: ps.src,
userListId: userList ? userList.id : null, userListId: ps.userListId !== undefined ? userList ? userList.id : null : undefined,
keywords: ps.keywords, keywords: ps.keywords,
excludeKeywords: ps.excludeKeywords, excludeKeywords: ps.excludeKeywords,
users: ps.users, users: ps.users,
caseSensitive: ps.caseSensitive, caseSensitive: ps.caseSensitive,
localOnly: ps.localOnly, localOnly: ps.localOnly,
excludeBots: ps.excludeBots,
withReplies: ps.withReplies, withReplies: ps.withReplies,
withFile: ps.withFile, withFile: ps.withFile,
notify: ps.notify, notify: ps.notify,

View File

@ -44,6 +44,7 @@ export const paramDef = {
permissions: { type: 'array', items: { permissions: { type: 'array', items: {
type: 'string', type: 'string',
} }, } },
visibility: { type: 'string', enum: ['public', 'private'], default: 'public' },
}, },
required: ['title', 'summary', 'script', 'permissions'], required: ['title', 'summary', 'script', 'permissions'],
} as const; } as const;
@ -66,6 +67,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
summary: ps.summary, summary: ps.summary,
script: ps.script, script: ps.script,
permissions: ps.permissions, permissions: ps.permissions,
visibility: ps.visibility,
}).then(x => this.flashsRepository.findOneByOrFail(x.identifiers[0])); }).then(x => this.flashsRepository.findOneByOrFail(x.identifiers[0]));
return await this.flashEntityService.pack(flash); return await this.flashEntityService.pack(flash);

View File

@ -132,11 +132,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private userEntityService: UserEntityService, private userEntityService: UserEntityService,
) { ) {
super(meta, paramDef, async (ps, me) => { super(meta, paramDef, async (ps, me) => {
const ids = Array.isArray(ps.userId) ? ps.userId : [ps.userId]; return Array.isArray(ps.userId)
? await this.userEntityService.getRelations(me.id, ps.userId).then(it => [...it.values()])
const relations = await Promise.all(ids.map(id => this.userEntityService.getRelation(me.id, id))); : await this.userEntityService.getRelation(me.id, ps.userId).then(it => [it]);
return Array.isArray(ps.userId) ? relations : relations[0];
}); });
} }
} }

View File

@ -5,6 +5,7 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { summaly } from '@misskey-dev/summaly'; import { summaly } from '@misskey-dev/summaly';
import { SummalyResult } from '@misskey-dev/summaly/built/summary.js';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import type { Config } from '@/config.js'; import type { Config } from '@/config.js';
import { MetaService } from '@/core/MetaService.js'; import { MetaService } from '@/core/MetaService.js';
@ -14,6 +15,7 @@ import { query } from '@/misc/prelude/url.js';
import { LoggerService } from '@/core/LoggerService.js'; import { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js'; import { bindThis } from '@/decorators.js';
import { ApiError } from '@/server/api/error.js'; import { ApiError } from '@/server/api/error.js';
import { MiMeta } from '@/models/Meta.js';
import type { FastifyRequest, FastifyReply } from 'fastify'; import type { FastifyRequest, FastifyReply } from 'fastify';
@Injectable() @Injectable()
@ -62,24 +64,25 @@ export class UrlPreviewService {
const meta = await this.metaService.fetch(); const meta = await this.metaService.fetch();
this.logger.info(meta.summalyProxy if (!meta.urlPreviewEnabled) {
reply.code(403);
return {
error: new ApiError({
message: 'URL preview is disabled',
code: 'URL_PREVIEW_DISABLED',
id: '58b36e13-d2f5-0323-b0c6-76aa9dabefb8',
}),
};
}
this.logger.info(meta.urlPreviewSummaryProxyUrl
? `(Proxy) Getting preview of ${url}@${lang} ...` ? `(Proxy) Getting preview of ${url}@${lang} ...`
: `Getting preview of ${url}@${lang} ...`); : `Getting preview of ${url}@${lang} ...`);
try { try {
const summary = meta.summalyProxy ? const summary = meta.urlPreviewSummaryProxyUrl
await this.httpRequestService.getJson<ReturnType<typeof summaly>>(`${meta.summalyProxy}?${query({ ? await this.fetchSummaryFromProxy(url, meta, lang)
url: url, : await this.fetchSummary(url, meta, lang);
lang: lang ?? 'ja-JP',
})}`)
:
await summaly(url, {
followRedirects: false,
lang: lang ?? 'ja-JP',
agent: this.config.proxy ? {
http: this.httpRequestService.httpAgent,
https: this.httpRequestService.httpsAgent,
} : undefined,
});
this.logger.succ(`Got preview of ${url}: ${summary.title}`); this.logger.succ(`Got preview of ${url}: ${summary.title}`);
@ -100,6 +103,7 @@ export class UrlPreviewService {
return summary; return summary;
} catch (err) { } catch (err) {
this.logger.warn(`Failed to get preview of ${url}: ${err}`); this.logger.warn(`Failed to get preview of ${url}: ${err}`);
reply.code(422); reply.code(422);
reply.header('Cache-Control', 'max-age=86400, immutable'); reply.header('Cache-Control', 'max-age=86400, immutable');
return { return {
@ -111,4 +115,37 @@ export class UrlPreviewService {
}; };
} }
} }
private fetchSummary(url: string, meta: MiMeta, lang?: string): Promise<SummalyResult> {
const agent = this.config.proxy
? {
http: this.httpRequestService.httpAgent,
https: this.httpRequestService.httpsAgent,
}
: undefined;
return summaly(url, {
followRedirects: false,
lang: lang ?? 'ja-JP',
agent: agent,
userAgent: meta.urlPreviewUserAgent ?? undefined,
operationTimeout: meta.urlPreviewTimeout,
contentLengthLimit: meta.urlPreviewMaximumContentLength,
contentLengthRequired: meta.urlPreviewRequireContentLength,
});
}
private fetchSummaryFromProxy(url: string, meta: MiMeta, lang?: string): Promise<SummalyResult> {
const proxy = meta.urlPreviewSummaryProxyUrl!;
const queryStr = query({
url: url,
lang: lang ?? 'ja-JP',
userAgent: meta.urlPreviewUserAgent ?? undefined,
operationTimeout: meta.urlPreviewTimeout,
contentLengthLimit: meta.urlPreviewMaximumContentLength,
contentLengthRequired: meta.urlPreviewRequireContentLength,
});
return this.httpRequestService.getJson<SummalyResult>(`${proxy}?${queryStr}`);
}
} }

View File

@ -86,8 +86,8 @@
//#endregion //#endregion
//#region Script //#region Script
function importAppScript() { async function importAppScript() {
import(`/vite/${CLIENT_ENTRY}`) await import(`/vite/${CLIENT_ENTRY}`)
.catch(async e => { .catch(async e => {
console.error(e); console.error(e);
renderError('APP_IMPORT', e); renderError('APP_IMPORT', e);

View File

@ -2,7 +2,7 @@ extends ./base
block vars block vars
- const user = note.user; - const user = note.user;
- const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`; - const title = user.name ? `${user.name} (@${user.username}${user.host ? `@${user.host}` : ''})` : `@${user.username}${user.host ? `@${user.host}` : ''}`;
- const url = `${config.url}/notes/${note.id}`; - const url = `${config.url}/notes/${note.id}`;
- const isRenote = note.renote && note.text == null && note.fileIds.length == 0 && note.poll == null; - const isRenote = note.renote && note.text == null && note.fileIds.length == 0 && note.poll == null;
- const images = (note.files || []).filter(file => file.type.startsWith('image/') && !file.isSensitive) - const images = (note.files || []).filter(file => file.type.startsWith('image/') && !file.isSensitive)
@ -28,7 +28,7 @@ block og
// FIXME: add embed player for Twitter // FIXME: add embed player for Twitter
if images.length if images.length
meta(property='twitter:card' content='summary_large_image') meta(property='twitter:card' content='summary_large_image')
each image in images each image in images
meta(property='og:image' content= image.url) meta(property='og:image' content= image.url)
else else
meta(property='twitter:card' content='summary') meta(property='twitter:card' content='summary')

View File

@ -1,7 +1,7 @@
extends ./base extends ./base
block vars block vars
- const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`; - const title = user.name ? `${user.name} (@${user.username}${user.host ? `@${user.host}` : ''})` : `@${user.username}${user.host ? `@${user.host}` : ''}`;
- const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`; - const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`;
block title block title

View File

@ -44,6 +44,7 @@ describe('アンテナ', () => {
users: [''], users: [''],
withFile: false, withFile: false,
withReplies: false, withReplies: false,
excludeBots: false,
}; };
let root: User; let root: User;
@ -156,6 +157,7 @@ describe('アンテナ', () => {
users: [''], users: [''],
withFile: false, withFile: false,
withReplies: false, withReplies: false,
excludeBots: false,
localOnly: false, localOnly: false,
}; };
assert.deepStrictEqual(response, expected); assert.deepStrictEqual(response, expected);

View File

@ -472,7 +472,7 @@ describe('Note', () => {
priority: 0, priority: 0,
value: true, value: true,
}, },
}, } as any,
}, alice); }, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
@ -784,7 +784,7 @@ describe('Note', () => {
priority: 1, priority: 1,
value: 0, value: 0,
}, },
}, } as any,
}, alice); }, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
@ -838,7 +838,7 @@ describe('Note', () => {
priority: 1, priority: 1,
value: 0, value: 0,
}, },
}, } as any,
}, alice); }, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);
@ -894,7 +894,7 @@ describe('Note', () => {
priority: 1, priority: 1,
value: 1, value: 1,
}, },
}, } as any,
}, alice); }, alice);
assert.strictEqual(res.status, 200); assert.strictEqual(res.status, 200);

View File

@ -890,17 +890,35 @@ describe('Timelines', () => {
const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body); const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body);
await api('users/lists/push', { listId: list.id, userId: bob.id }, alice); await api('users/lists/push', { listId: list.id, userId: bob.id }, alice);
await api('users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: false }, alice);
await sleep(1000); await sleep(1000);
const aliceNote = await post(alice, { text: 'hi' }); const aliceNote = await post(alice, { text: 'hi' });
const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id }); const bobNote = await post(bob, { text: 'hi', replyId: aliceNote.id });
await waitForPushToTl(); await waitForPushToTl();
const res = await api('notes/user-list-timeline', { listId: list.id, withReplies: false }, alice); const res = await api('notes/user-list-timeline', { listId: list.id }, alice);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true); assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), true);
}); });
test.concurrent('withReplies: false でリスインしているフォローしていないユーザーの他人への返信が含まれない', async () => {
const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]);
const list = await api('users/lists/create', { name: 'list' }, alice).then(res => res.body);
await api('users/lists/push', { listId: list.id, userId: bob.id }, alice);
await api('users/lists/update-membership', { listId: list.id, userId: bob.id, withReplies: false }, alice);
await sleep(1000);
const carolNote = await post(carol, { text: 'hi' });
const bobNote = await post(bob, { text: 'hi', replyId: carolNote.id });
await waitForPushToTl();
const res = await api('notes/user-list-timeline', { listId: list.id }, alice);
assert.strictEqual(res.body.some((note: any) => note.id === bobNote.id), false);
});
test.concurrent('withReplies: true でリスインしているフォローしていないユーザーの他人への返信が含まれる', async () => { test.concurrent('withReplies: true でリスインしているフォローしていないユーザーの他人への返信が含まれる', async () => {
const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]); const [alice, bob, carol] = await Promise.all([signup(), signup(), signup()]);

7
packages/backend/test/global.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type FIXME = any;

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { initTestDb, sendEnvResetRequest } from './utils.js'; import { initTestDb, sendEnvResetRequest } from './utils.js';
beforeAll(async () => { beforeAll(async () => {

View File

@ -4,10 +4,10 @@
*/ */
import Ajv from 'ajv'; import Ajv from 'ajv';
import { Schema } from '@/misc/schema'; import { Schema } from '@/misc/json-schema.js';
export const getValidator = (paramDef: Schema) => { export const getValidator = (paramDef: Schema) => {
const ajv = new Ajv({ const ajv = new Ajv.default({
useDefaults: true, useDefaults: true,
}); });
ajv.addFormat('misskey:id', /^[a-zA-Z0-9]+$/); ajv.addFormat('misskey:id', /^[a-zA-Z0-9]+$/);

View File

@ -5,7 +5,7 @@
"noImplicitAny": true, "noImplicitAny": true,
"noImplicitReturns": true, "noImplicitReturns": true,
"noUnusedParameters": false, "noUnusedParameters": false,
"noUnusedLocals": true, "noUnusedLocals": false,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"declaration": false, "declaration": false,
"sourceMap": true, "sourceMap": true,
@ -18,6 +18,7 @@
"strict": true, "strict": true,
"strictNullChecks": true, "strictNullChecks": true,
"strictPropertyInitialization": false, "strictPropertyInitialization": false,
"skipLibCheck": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"resolveJsonModule": true, "resolveJsonModule": true,

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import * as assert from 'assert'; import * as assert from 'assert';
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';

View File

@ -90,7 +90,8 @@ describe('RelayService', () => {
expect(queueService.deliver).toHaveBeenCalled(); expect(queueService.deliver).toHaveBeenCalled();
expect(queueService.deliver.mock.lastCall![1]?.type).toBe('Undo'); expect(queueService.deliver.mock.lastCall![1]?.type).toBe('Undo');
expect(queueService.deliver.mock.lastCall![1]?.object.type).toBe('Follow'); expect(typeof queueService.deliver.mock.lastCall![1]?.object).toBe('object');
expect((queueService.deliver.mock.lastCall![1]?.object as any).type).toBe('Follow');
expect(queueService.deliver.mock.lastCall![2]).toBe('https://example.com'); expect(queueService.deliver.mock.lastCall![2]).toBe('https://example.com');
//expect(queueService.deliver.mock.lastCall![0].username).toBe('relay.actor'); //expect(queueService.deliver.mock.lastCall![0].username).toBe('relay.actor');

View File

@ -0,0 +1,528 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Test, TestingModule } from '@nestjs/testing';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { GlobalModule } from '@/GlobalModule.js';
import { CoreModule } from '@/core/CoreModule.js';
import type { MiUser } from '@/models/User.js';
import { secureRndstr } from '@/misc/secure-rndstr.js';
import { genAidx } from '@/misc/id/aidx.js';
import {
BlockingsRepository,
FollowingsRepository, FollowRequestsRepository,
MiUserProfile, MutingsRepository, RenoteMutingsRepository,
UserMemoRepository,
UserProfilesRepository,
UsersRepository,
} from '@/models/_.js';
import { DI } from '@/di-symbols.js';
import { AvatarDecorationService } from '@/core/AvatarDecorationService.js';
import { ApPersonService } from '@/core/activitypub/models/ApPersonService.js';
import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
import { PageEntityService } from '@/core/entities/PageEntityService.js';
import { CustomEmojiService } from '@/core/CustomEmojiService.js';
import { AnnouncementService } from '@/core/AnnouncementService.js';
import { RoleService } from '@/core/RoleService.js';
import { FederatedInstanceService } from '@/core/FederatedInstanceService.js';
import { IdService } from '@/core/IdService.js';
import { UtilityService } from '@/core/UtilityService.js';
import { EmojiEntityService } from '@/core/entities/EmojiEntityService.js';
import { ModerationLogService } from '@/core/ModerationLogService.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
import { MetaService } from '@/core/MetaService.js';
import { FetchInstanceMetadataService } from '@/core/FetchInstanceMetadataService.js';
import { CacheService } from '@/core/CacheService.js';
import { ApResolverService } from '@/core/activitypub/ApResolverService.js';
import { ApNoteService } from '@/core/activitypub/models/ApNoteService.js';
import { ApImageService } from '@/core/activitypub/models/ApImageService.js';
import { ApMfmService } from '@/core/activitypub/ApMfmService.js';
import { MfmService } from '@/core/MfmService.js';
import { HashtagService } from '@/core/HashtagService.js';
import UsersChart from '@/core/chart/charts/users.js';
import { ChartLoggerService } from '@/core/chart/ChartLoggerService.js';
import InstanceChart from '@/core/chart/charts/instance.js';
import { ApLoggerService } from '@/core/activitypub/ApLoggerService.js';
import { AccountMoveService } from '@/core/AccountMoveService.js';
import { ReactionService } from '@/core/ReactionService.js';
import { NotificationService } from '@/core/NotificationService.js';
process.env.NODE_ENV = 'test';
describe('UserEntityService', () => {
describe('pack/packMany', () => {
let app: TestingModule;
let service: UserEntityService;
let usersRepository: UsersRepository;
let userProfileRepository: UserProfilesRepository;
let userMemosRepository: UserMemoRepository;
let followingRepository: FollowingsRepository;
let followingRequestRepository: FollowRequestsRepository;
let blockingRepository: BlockingsRepository;
let mutingRepository: MutingsRepository;
let renoteMutingsRepository: RenoteMutingsRepository;
async function createUser(userData: Partial<MiUser> = {}, profileData: Partial<MiUserProfile> = {}) {
const un = secureRndstr(16);
const user = await usersRepository
.insert({
...userData,
id: genAidx(Date.now()),
username: un,
usernameLower: un,
})
.then(x => usersRepository.findOneByOrFail(x.identifiers[0]));
await userProfileRepository.insert({
...profileData,
userId: user.id,
});
return user;
}
async function memo(writer: MiUser, target: MiUser, memo: string) {
await userMemosRepository.insert({
id: genAidx(Date.now()),
userId: writer.id,
targetUserId: target.id,
memo,
});
}
async function follow(follower: MiUser, followee: MiUser) {
await followingRepository.insert({
id: genAidx(Date.now()),
followerId: follower.id,
followeeId: followee.id,
});
}
async function requestFollow(requester: MiUser, requestee: MiUser) {
await followingRequestRepository.insert({
id: genAidx(Date.now()),
followerId: requester.id,
followeeId: requestee.id,
});
}
async function block(blocker: MiUser, blockee: MiUser) {
await blockingRepository.insert({
id: genAidx(Date.now()),
blockerId: blocker.id,
blockeeId: blockee.id,
});
}
async function mute(mutant: MiUser, mutee: MiUser) {
await mutingRepository.insert({
id: genAidx(Date.now()),
muterId: mutant.id,
muteeId: mutee.id,
});
}
async function muteRenote(mutant: MiUser, mutee: MiUser) {
await renoteMutingsRepository.insert({
id: genAidx(Date.now()),
muterId: mutant.id,
muteeId: mutee.id,
});
}
function randomIntRange(weight = 10) {
return [...Array(Math.floor(Math.random() * weight))].map((it, idx) => idx);
}
beforeAll(async () => {
const services = [
UserEntityService,
ApPersonService,
NoteEntityService,
PageEntityService,
CustomEmojiService,
AnnouncementService,
RoleService,
FederatedInstanceService,
IdService,
AvatarDecorationService,
UtilityService,
EmojiEntityService,
ModerationLogService,
GlobalEventService,
DriveFileEntityService,
MetaService,
FetchInstanceMetadataService,
CacheService,
ApResolverService,
ApNoteService,
ApImageService,
ApMfmService,
MfmService,
HashtagService,
UsersChart,
ChartLoggerService,
InstanceChart,
ApLoggerService,
AccountMoveService,
ReactionService,
NotificationService,
];
app = await Test.createTestingModule({
imports: [GlobalModule, CoreModule],
providers: [
...services,
...services.map(x => ({ provide: x.name, useExisting: x })),
],
}).compile();
await app.init();
app.enableShutdownHooks();
service = app.get<UserEntityService>(UserEntityService);
usersRepository = app.get<UsersRepository>(DI.usersRepository);
userProfileRepository = app.get<UserProfilesRepository>(DI.userProfilesRepository);
userMemosRepository = app.get<UserMemoRepository>(DI.userMemosRepository);
followingRepository = app.get<FollowingsRepository>(DI.followingsRepository);
followingRequestRepository = app.get<FollowRequestsRepository>(DI.followRequestsRepository);
blockingRepository = app.get<BlockingsRepository>(DI.blockingsRepository);
mutingRepository = app.get<MutingsRepository>(DI.mutingsRepository);
renoteMutingsRepository = app.get<RenoteMutingsRepository>(DI.renoteMutingsRepository);
});
afterAll(async () => {
await app.close();
});
test('UserLite', async() => {
const me = await createUser();
const who = await createUser();
await memo(me, who, 'memo');
const actual = await service.pack(who, me, { schema: 'UserLite' }) as any;
// no detail
expect(actual.memo).toBeUndefined();
// no detail and me
expect(actual.birthday).toBeUndefined();
// no detail and me
expect(actual.achievements).toBeUndefined();
});
test('UserDetailedNotMe', async() => {
const me = await createUser();
const who = await createUser({}, { birthday: '2000-01-01' });
await memo(me, who, 'memo');
const actual = await service.pack(who, me, { schema: 'UserDetailedNotMe' }) as any;
// is detail
expect(actual.memo).toBe('memo');
// is detail
expect(actual.birthday).toBe('2000-01-01');
// no detail and me
expect(actual.achievements).toBeUndefined();
});
test('MeDetailed', async() => {
const achievements = [{ name: 'achievement', unlockedAt: new Date().getTime() }];
const me = await createUser({}, {
birthday: '2000-01-01',
achievements: achievements,
});
await memo(me, me, 'memo');
const actual = await service.pack(me, me, { schema: 'MeDetailed' }) as any;
// is detail
expect(actual.memo).toBe('memo');
// is detail
expect(actual.birthday).toBe('2000-01-01');
// is detail and me
expect(actual.achievements).toEqual(achievements);
});
describe('packManyによるpreloadがある時、preloadが無い時とpackの結果が同じになるか見たい', () => {
test('no-preload', async() => {
const me = await createUser();
// meがフォローしてる人たち
const followeeMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of followeeMe) {
await follow(me, who);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(true);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meをフォローしてる人たち
const followerMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of followerMe) {
await follow(who, me);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(true);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meがフォローリクエストを送った人たち
const requestsFromYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of requestsFromYou) {
await requestFollow(me, who);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(true);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meにフォローリクエストを送った人たち
const requestsToYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of requestsToYou) {
await requestFollow(who, me);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(true);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meがブロックしてる人たち
const blockingYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of blockingYou) {
await block(me, who);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(true);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meをブロックしてる人たち
const blockingMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of blockingMe) {
await block(who, me);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(true);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
// meがミュートしてる人たち
const muters = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of muters) {
await mute(me, who);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(true);
expect(actual.isRenoteMuted).toBe(false);
}
// meがリートミュートしてる人たち
const renoteMuters = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of renoteMuters) {
await muteRenote(me, who);
const actual = await service.pack(who, me, { schema: 'UserDetailed' }) as any;
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(true);
}
});
test('preload', async() => {
const me = await createUser();
{
// meがフォローしてる人たち
const followeeMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of followeeMe) {
await follow(me, who);
}
const actualList = await service.packMany(followeeMe, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(true);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meをフォローしてる人たち
const followerMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of followerMe) {
await follow(who, me);
}
const actualList = await service.packMany(followerMe, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(true);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meがフォローリクエストを送った人たち
const requestsFromYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of requestsFromYou) {
await requestFollow(me, who);
}
const actualList = await service.packMany(requestsFromYou, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(true);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meにフォローリクエストを送った人たち
const requestsToYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of requestsToYou) {
await requestFollow(who, me);
}
const actualList = await service.packMany(requestsToYou, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(true);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meがブロックしてる人たち
const blockingYou = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of blockingYou) {
await block(me, who);
}
const actualList = await service.packMany(blockingYou, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(true);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meをブロックしてる人たち
const blockingMe = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of blockingMe) {
await block(who, me);
}
const actualList = await service.packMany(blockingMe, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(true);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meがミュートしてる人たち
const muters = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of muters) {
await mute(me, who);
}
const actualList = await service.packMany(muters, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(true);
expect(actual.isRenoteMuted).toBe(false);
}
}
{
// meがリートミュートしてる人たち
const renoteMuters = await Promise.all(randomIntRange().map(() => createUser()));
for (const who of renoteMuters) {
await muteRenote(me, who);
}
const actualList = await service.packMany(renoteMuters, me, { schema: 'UserDetailed' }) as any;
for (const actual of actualList) {
expect(actual.isFollowing).toBe(false);
expect(actual.isFollowed).toBe(false);
expect(actual.hasPendingFollowRequestFromYou).toBe(false);
expect(actual.hasPendingFollowRequestToYou).toBe(false);
expect(actual.isBlocking).toBe(false);
expect(actual.isBlocked).toBe(false);
expect(actual.isMuted).toBe(false);
expect(actual.isRenoteMuted).toBe(true);
}
}
});
});
});
});

View File

@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { DebounceLoader } from '@/misc/loader.js'; import { DebounceLoader } from '@/misc/loader.js';
class Mock { class Mock {

View File

@ -1,3 +1,8 @@
<!--
SPDX-FileCopyrightText: syuilo and misskey-project
SPDX-License-Identifier: AGPL-3.0-only
-->
<link rel="preload" href="https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/about-icon.png?raw=true" as="image" type="image/png" crossorigin="anonymous"> <link rel="preload" href="https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/about-icon.png?raw=true" as="image" type="image/png" crossorigin="anonymous">
<link rel="preload" href="https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/fedi.jpg?raw=true" as="image" type="image/jpeg" crossorigin="anonymous"> <link rel="preload" href="https://github.com/misskey-dev/misskey/blob/master/packages/frontend/assets/fedi.jpg?raw=true" as="image" type="image/jpeg" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/@tabler/icons-webfont@2.44.0/tabler-icons.min.css"> <link rel="stylesheet" href="https://unpkg.com/@tabler/icons-webfont@2.44.0/tabler-icons.min.css">

View File

@ -60,7 +60,7 @@
"rollup": "4.12.0", "rollup": "4.12.0",
"sanitize-html": "2.12.1", "sanitize-html": "2.12.1",
"sass": "1.71.1", "sass": "1.71.1",
"shiki": "1.1.7", "shiki": "1.2.0",
"strict-event-emitter-types": "2.0.0", "strict-event-emitter-types": "2.0.0",
"textarea-caret": "3.1.0", "textarea-caret": "3.1.0",
"three": "0.162.0", "three": "0.162.0",

View File

@ -154,8 +154,11 @@ export async function common(createVue: () => App<Element>) {
// NOTE: この処理は必ずクライアント更新チェック処理より後に来ること(テーマ再構築のため) // NOTE: この処理は必ずクライアント更新チェック処理より後に来ること(テーマ再構築のため)
watch(defaultStore.reactiveState.darkMode, (darkMode) => { watch(defaultStore.reactiveState.darkMode, (darkMode) => {
applyTheme(darkMode ? ColdDeviceStorage.get('darkTheme') : ColdDeviceStorage.get('lightTheme')); applyTheme(darkMode ? ColdDeviceStorage.get('darkTheme') : ColdDeviceStorage.get('lightTheme'));
document.documentElement.dataset.colorMode = darkMode ? 'dark' : 'light';
}, { immediate: miLocalStorage.getItem('theme') == null }); }, { immediate: miLocalStorage.getItem('theme') == null });
document.documentElement.dataset.colorMode = defaultStore.state.darkMode ? 'dark' : 'light';
const darkTheme = computed(ColdDeviceStorage.makeGetterSetter('darkTheme')); const darkTheme = computed(ColdDeviceStorage.makeGetterSetter('darkTheme'));
const lightTheme = computed(ColdDeviceStorage.makeGetterSetter('lightTheme')); const lightTheme = computed(ColdDeviceStorage.makeGetterSetter('lightTheme'));

View File

@ -75,27 +75,31 @@ export async function mainBoot() {
mainRouter.push('/search'); mainRouter.push('/search');
}, },
}; };
try {
if (defaultStore.state.enableSeasonalScreenEffect) { if (defaultStore.state.enableSeasonalScreenEffect) {
const month = new Date().getMonth() + 1; const month = new Date().getMonth() + 1;
if (defaultStore.state.hemisphere === 'S') { if (defaultStore.state.hemisphere === 'S') {
// ▼南半球 // ▼南半球
if (month === 7 || month === 8) { if (month === 7 || month === 8) {
const SnowfallEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect; const SnowfallEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect;
new SnowfallEffect({}).render(); new SnowfallEffect({}).render();
}
} else {
// ▼北半球
if (month === 12 || month === 1) {
const SnowfallEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect;
new SnowfallEffect({}).render();
} else if (month === 3 || month === 4) {
const SakuraEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect;
new SakuraEffect({
sakura: true,
}).render();
}
} }
} else { }
// ▼北半球 } catch (error) {
if (month === 12 || month === 1) { // console.error(error);
const SnowfallEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect; console.error('Failed to initialise the seasonal screen effect canvas context:', error);
new SnowfallEffect({}).render();
} else if (month === 3 || month === 4) {
const SakuraEffect = (await import('@/scripts/snowfall-effect.js')).SnowfallEffect;
new SakuraEffect({
sakura: true,
}).render();
}
}
} }
if ($i) { if ($i) {
@ -181,14 +185,26 @@ export async function mainBoot() {
if ($i.followersCount >= 500) claimAchievement('followers500'); if ($i.followersCount >= 500) claimAchievement('followers500');
if ($i.followersCount >= 1000) claimAchievement('followers1000'); if ($i.followersCount >= 1000) claimAchievement('followers1000');
if (Date.now() - new Date($i.createdAt).getTime() > 1000 * 60 * 60 * 24 * 365) { const createdAt = new Date($i.createdAt);
claimAchievement('passedSinceAccountCreated1'); const createdAtThreeYearsLater = new Date($i.createdAt);
} createdAtThreeYearsLater.setFullYear(createdAtThreeYearsLater.getFullYear() + 3);
if (Date.now() - new Date($i.createdAt).getTime() > 1000 * 60 * 60 * 24 * 365 * 2) { if (now >= createdAtThreeYearsLater) {
claimAchievement('passedSinceAccountCreated2');
}
if (Date.now() - new Date($i.createdAt).getTime() > 1000 * 60 * 60 * 24 * 365 * 3) {
claimAchievement('passedSinceAccountCreated3'); claimAchievement('passedSinceAccountCreated3');
claimAchievement('passedSinceAccountCreated2');
claimAchievement('passedSinceAccountCreated1');
} else {
const createdAtTwoYearsLater = new Date($i.createdAt);
createdAtTwoYearsLater.setFullYear(createdAtTwoYearsLater.getFullYear() + 2);
if (now >= createdAtTwoYearsLater) {
claimAchievement('passedSinceAccountCreated2');
claimAchievement('passedSinceAccountCreated1');
} else {
const createdAtOneYearLater = new Date($i.createdAt);
createdAtOneYearLater.setFullYear(createdAtOneYearLater.getFullYear() + 1);
if (now >= createdAtOneYearLater) {
claimAchievement('passedSinceAccountCreated1');
}
}
} }
if (claimedAchievements.length >= 30) { if (claimedAchievements.length >= 30) {
@ -223,7 +239,7 @@ export async function mainBoot() {
const latestDonationInfoShownAt = miLocalStorage.getItem('latestDonationInfoShownAt'); const latestDonationInfoShownAt = miLocalStorage.getItem('latestDonationInfoShownAt');
const neverShowDonationInfo = miLocalStorage.getItem('neverShowDonationInfo'); const neverShowDonationInfo = miLocalStorage.getItem('neverShowDonationInfo');
if (neverShowDonationInfo !== 'true' && (new Date($i.createdAt).getTime() < (Date.now() - (1000 * 60 * 60 * 24 * 3))) && !location.pathname.startsWith('/miauth')) { if (neverShowDonationInfo !== 'true' && (createdAt.getTime() < (Date.now() - (1000 * 60 * 60 * 24 * 3))) && !location.pathname.startsWith('/miauth')) {
if (latestDonationInfoShownAt == null || (new Date(latestDonationInfoShownAt).getTime() < (Date.now() - (1000 * 60 * 60 * 24 * 30)))) { if (latestDonationInfoShownAt == null || (new Date(latestDonationInfoShownAt).getTime() < (Date.now() - (1000 * 60 * 60 * 24 * 30)))) {
popup(defineAsyncComponent(() => import('@/components/MkDonation.vue')), {}, {}, 'closed'); popup(defineAsyncComponent(() => import('@/components/MkDonation.vue')), {}, {}, 'closed');
} }

View File

@ -9,9 +9,9 @@ SPDX-License-Identifier: AGPL-3.0-only
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref, computed, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { bundledLanguagesInfo } from 'shiki'; import { bundledLanguagesInfo } from 'shiki/langs';
import type { BuiltinLanguage } from 'shiki'; import type { BundledLanguage } from 'shiki/langs';
import { getHighlighter, getTheme } from '@/scripts/code-highlighter.js'; import { getHighlighter, getTheme } from '@/scripts/code-highlighter.js';
import { defaultStore } from '@/store.js'; import { defaultStore } from '@/store.js';
@ -23,7 +23,7 @@ const props = defineProps<{
const highlighter = await getHighlighter(); const highlighter = await getHighlighter();
const darkMode = defaultStore.reactiveState.darkMode; const darkMode = defaultStore.reactiveState.darkMode;
const codeLang = ref<BuiltinLanguage | 'aiscript'>('js'); const codeLang = ref<BundledLanguage | 'aiscript'>('js');
const [lightThemeName, darkThemeName] = await Promise.all([ const [lightThemeName, darkThemeName] = await Promise.all([
getTheme('light', true), getTheme('light', true),
@ -42,7 +42,7 @@ const html = computed(() => highlighter.codeToHtml(props.code, {
})); }));
async function fetchLanguage(to: string): Promise<void> { async function fetchLanguage(to: string): Promise<void> {
const language = to as BuiltinLanguage; const language = to as BundledLanguage;
// Check for the loaded languages, and load the language if it's not loaded yet. // Check for the loaded languages, and load the language if it's not loaded yet.
if (!highlighter.getLoadedLanguages().includes(language)) { if (!highlighter.getLoadedLanguages().includes(language)) {

View File

@ -22,6 +22,7 @@ SPDX-License-Identifier: AGPL-3.0-only
:autocomplete="autocomplete" :autocomplete="autocomplete"
:autocapitalize="autocapitalize" :autocapitalize="autocapitalize"
:spellcheck="spellcheck" :spellcheck="spellcheck"
:inputmode="inputmode"
:step="step" :step="step"
:list="id" :list="id"
:min="min" :min="min"
@ -63,6 +64,7 @@ const props = defineProps<{
mfmAutocomplete?: boolean | SuggestionType[], mfmAutocomplete?: boolean | SuggestionType[],
autocapitalize?: string; autocapitalize?: string;
spellcheck?: boolean; spellcheck?: boolean;
inputmode?: 'none' | 'text' | 'search' | 'email' | 'url' | 'numeric' | 'tel' | 'decimal';
step?: any; step?: any;
datalist?: string[]; datalist?: string[];
min?: number; min?: number;

View File

@ -18,6 +18,7 @@ import { defineAsyncComponent, ref } from 'vue';
import { url as local } from '@/config.js'; import { url as local } from '@/config.js';
import { useTooltip } from '@/scripts/use-tooltip.js'; import { useTooltip } from '@/scripts/use-tooltip.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
import { isEnabledUrlPreview } from '@/instance.js';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
url: string; url: string;
@ -29,15 +30,17 @@ const self = props.url.startsWith(local);
const attr = self ? 'to' : 'href'; const attr = self ? 'to' : 'href';
const target = self ? null : '_blank'; const target = self ? null : '_blank';
const el = ref<HTMLElement>(); const el = ref<HTMLElement | { $el: HTMLElement }>();
useTooltip(el, (showing) => { if (isEnabledUrlPreview.value) {
os.popup(defineAsyncComponent(() => import('@/components/MkUrlPreviewPopup.vue')), { useTooltip(el, (showing) => {
showing, os.popup(defineAsyncComponent(() => import('@/components/MkUrlPreviewPopup.vue')), {
url: props.url, showing,
source: el.value, url: props.url,
}, {}, 'closed'); source: el.value instanceof HTMLElement ? el.value : el.value?.$el,
}); }, {}, 'closed');
});
}
</script> </script>
<style lang="scss" module> <style lang="scss" module>

View File

@ -82,7 +82,9 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkMediaList :mediaList="appearNote.files"/> <MkMediaList :mediaList="appearNote.files"/>
</div> </div>
<MkPoll v-if="appearNote.poll" :noteId="appearNote.id" :poll="appearNote.poll" :class="$style.poll"/> <MkPoll v-if="appearNote.poll" :noteId="appearNote.id" :poll="appearNote.poll" :class="$style.poll"/>
<MkUrlPreview v-for="url in urls" :key="url" :url="url" :compact="true" :detail="false" :class="$style.urlPreview"/> <div v-if="isEnabledUrlPreview">
<MkUrlPreview v-for="url in urls" :key="url" :url="url" :compact="true" :detail="false" :class="$style.urlPreview"/>
</div>
<div v-if="appearNote.renote" :class="$style.quote"><MkNoteSimple :note="appearNote.renote" :class="$style.quoteNote"/></div> <div v-if="appearNote.renote" :class="$style.quote"><MkNoteSimple :note="appearNote.renote" :class="$style.quoteNote"/></div>
<button v-if="isLong && collapsed" :class="$style.collapsed" class="_button" @click="collapsed = false"> <button v-if="isLong && collapsed" :class="$style.collapsed" class="_button" @click="collapsed = false">
<span :class="$style.collapsedLabel">{{ i18n.ts.showMore }}</span> <span :class="$style.collapsedLabel">{{ i18n.ts.showMore }}</span>
@ -93,7 +95,7 @@ SPDX-License-Identifier: AGPL-3.0-only
</div> </div>
<MkA v-if="appearNote.channel && !inChannel" :class="$style.channel" :to="`/channels/${appearNote.channel.id}`"><i class="ti ti-device-tv"></i> {{ appearNote.channel.name }}</MkA> <MkA v-if="appearNote.channel && !inChannel" :class="$style.channel" :to="`/channels/${appearNote.channel.id}`"><i class="ti ti-device-tv"></i> {{ appearNote.channel.name }}</MkA>
</div> </div>
<MkReactionsViewer :note="appearNote" :maxNumber="16" @mockUpdateMyReaction="emitUpdReaction"> <MkReactionsViewer v-if="appearNote.reactionAcceptance !== 'likeOnly'" :note="appearNote" :maxNumber="16" @mockUpdateMyReaction="emitUpdReaction">
<template #more> <template #more>
<div :class="$style.reactionOmitted">{{ i18n.ts.more }}</div> <div :class="$style.reactionOmitted">{{ i18n.ts.more }}</div>
</template> </template>
@ -101,7 +103,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<footer :class="$style.footer"> <footer :class="$style.footer">
<button :class="$style.footerButton" class="_button" @click="reply()"> <button :class="$style.footerButton" class="_button" @click="reply()">
<i class="ti ti-arrow-back-up"></i> <i class="ti ti-arrow-back-up"></i>
<p v-if="appearNote.repliesCount > 0" :class="$style.footerButtonCount">{{ appearNote.repliesCount }}</p> <p v-if="appearNote.repliesCount > 0" :class="$style.footerButtonCount">{{ number(appearNote.repliesCount) }}</p>
</button> </button>
<button <button
v-if="canRenote" v-if="canRenote"
@ -111,17 +113,17 @@ SPDX-License-Identifier: AGPL-3.0-only
@mousedown="renote()" @mousedown="renote()"
> >
<i class="ti ti-repeat"></i> <i class="ti ti-repeat"></i>
<p v-if="appearNote.renoteCount > 0" :class="$style.footerButtonCount">{{ appearNote.renoteCount }}</p> <p v-if="appearNote.renoteCount > 0" :class="$style.footerButtonCount">{{ number(appearNote.renoteCount) }}</p>
</button> </button>
<button v-else :class="$style.footerButton" class="_button" disabled> <button v-else :class="$style.footerButton" class="_button" disabled>
<i class="ti ti-ban"></i> <i class="ti ti-ban"></i>
</button> </button>
<button v-if="appearNote.myReaction == null" ref="reactButton" :class="$style.footerButton" class="_button" @mousedown="react()"> <button ref="reactButton" :class="$style.footerButton" class="_button" @click="toggleReact()">
<i v-if="appearNote.reactionAcceptance === 'likeOnly'" class="ti ti-heart"></i> <i v-if="appearNote.reactionAcceptance === 'likeOnly' && appearNote.myReaction != null" class="ti ti-heart-filled" style="color: var(--eventReactionHeart);"></i>
<i v-else-if="appearNote.myReaction != null" class="ti ti-minus" style="color: var(--accent);"></i>
<i v-else-if="appearNote.reactionAcceptance === 'likeOnly'" class="ti ti-heart"></i>
<i v-else class="ti ti-plus"></i> <i v-else class="ti ti-plus"></i>
</button> <p v-if="(appearNote.reactionAcceptance === 'likeOnly' || defaultStore.state.showReactionsCount) && appearNote.reactionCount > 0" :class="$style.footerButtonCount">{{ number(appearNote.reactionCount) }}</p>
<button v-if="appearNote.myReaction != null" ref="reactButton" :class="$style.footerButton" class="_button" @click="undoReact(appearNote)">
<i class="ti ti-minus"></i>
</button> </button>
<button v-if="defaultStore.state.showClipButtonInNoteFooter" ref="clipButton" :class="$style.footerButton" class="_button" @mousedown="clip()"> <button v-if="defaultStore.state.showClipButtonInNoteFooter" ref="clipButton" :class="$style.footerButton" class="_button" @mousedown="clip()">
<i class="ti ti-paperclip"></i> <i class="ti ti-paperclip"></i>
@ -175,6 +177,7 @@ import { pleaseLogin } from '@/scripts/please-login.js';
import { focusPrev, focusNext } from '@/scripts/focus.js'; import { focusPrev, focusNext } from '@/scripts/focus.js';
import { checkWordMute } from '@/scripts/check-word-mute.js'; import { checkWordMute } from '@/scripts/check-word-mute.js';
import { userPage } from '@/filters/user.js'; import { userPage } from '@/filters/user.js';
import number from '@/filters/number.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
import * as sound from '@/scripts/sound.js'; import * as sound from '@/scripts/sound.js';
import { misskeyApi } from '@/scripts/misskey-api.js'; import { misskeyApi } from '@/scripts/misskey-api.js';
@ -193,6 +196,7 @@ import { MenuItem } from '@/types/menu.js';
import MkRippleEffect from '@/components/MkRippleEffect.vue'; import MkRippleEffect from '@/components/MkRippleEffect.vue';
import { showMovedDialog } from '@/scripts/show-moved-dialog.js'; import { showMovedDialog } from '@/scripts/show-moved-dialog.js';
import { shouldCollapsed } from '@/scripts/collapsed.js'; import { shouldCollapsed } from '@/scripts/collapsed.js';
import { isEnabledUrlPreview } from '@/instance.js';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
note: Misskey.entities.Note; note: Misskey.entities.Note;
@ -267,7 +271,7 @@ const renoteCollapsed = ref(
defaultStore.state.collapseRenotes && isRenote && ( defaultStore.state.collapseRenotes && isRenote && (
($i && ($i.id === note.value.userId || $i.id === appearNote.value.userId)) || // `||` must be `||`! See https://github.com/misskey-dev/misskey/issues/13131 ($i && ($i.id === note.value.userId || $i.id === appearNote.value.userId)) || // `||` must be `||`! See https://github.com/misskey-dev/misskey/issues/13131
(appearNote.value.myReaction != null) (appearNote.value.myReaction != null)
) ),
); );
/* Overload FunctionLint /* Overload FunctionLint
@ -420,6 +424,14 @@ function undoReact(targetNote: Misskey.entities.Note): void {
}); });
} }
function toggleReact() {
if (appearNote.value.myReaction == null) {
react();
} else {
undoReact(appearNote.value);
}
}
function onContextmenu(ev: MouseEvent): void { function onContextmenu(ev: MouseEvent): void {
if (props.mock) { if (props.mock) {
return; return;

View File

@ -95,7 +95,9 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkMediaList :mediaList="appearNote.files"/> <MkMediaList :mediaList="appearNote.files"/>
</div> </div>
<MkPoll v-if="appearNote.poll" ref="pollViewer" :noteId="appearNote.id" :poll="appearNote.poll" :class="$style.poll"/> <MkPoll v-if="appearNote.poll" ref="pollViewer" :noteId="appearNote.id" :poll="appearNote.poll" :class="$style.poll"/>
<MkUrlPreview v-for="url in urls" :key="url" :url="url" :compact="true" :detail="true" style="margin-top: 6px;"/> <div v-if="isEnabledUrlPreview">
<MkUrlPreview v-for="url in urls" :key="url" :url="url" :compact="true" :detail="true" style="margin-top: 6px;"/>
</div>
<div v-if="appearNote.renote" :class="$style.quote"><MkNoteSimple :note="appearNote.renote" :class="$style.quoteNote"/></div> <div v-if="appearNote.renote" :class="$style.quote"><MkNoteSimple :note="appearNote.renote" :class="$style.quoteNote"/></div>
</div> </div>
<MkA v-if="appearNote.channel && !inChannel" :class="$style.channel" :to="`/channels/${appearNote.channel.id}`"><i class="ti ti-device-tv"></i> {{ appearNote.channel.name }}</MkA> <MkA v-if="appearNote.channel && !inChannel" :class="$style.channel" :to="`/channels/${appearNote.channel.id}`"><i class="ti ti-device-tv"></i> {{ appearNote.channel.name }}</MkA>
@ -106,10 +108,10 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkTime :time="appearNote.createdAt" mode="detail" colored/> <MkTime :time="appearNote.createdAt" mode="detail" colored/>
</MkA> </MkA>
</div> </div>
<MkReactionsViewer ref="reactionsViewer" :note="appearNote"/> <MkReactionsViewer v-if="appearNote.reactionAcceptance !== 'likeOnly'" ref="reactionsViewer" :note="appearNote"/>
<button class="_button" :class="$style.noteFooterButton" @click="reply()"> <button class="_button" :class="$style.noteFooterButton" @click="reply()">
<i class="ti ti-arrow-back-up"></i> <i class="ti ti-arrow-back-up"></i>
<p v-if="appearNote.repliesCount > 0" :class="$style.noteFooterButtonCount">{{ appearNote.repliesCount }}</p> <p v-if="appearNote.repliesCount > 0" :class="$style.noteFooterButtonCount">{{ number(appearNote.repliesCount) }}</p>
</button> </button>
<button <button
v-if="canRenote" v-if="canRenote"
@ -119,17 +121,17 @@ SPDX-License-Identifier: AGPL-3.0-only
@mousedown="renote()" @mousedown="renote()"
> >
<i class="ti ti-repeat"></i> <i class="ti ti-repeat"></i>
<p v-if="appearNote.renoteCount > 0" :class="$style.noteFooterButtonCount">{{ appearNote.renoteCount }}</p> <p v-if="appearNote.renoteCount > 0" :class="$style.noteFooterButtonCount">{{ number(appearNote.renoteCount) }}</p>
</button> </button>
<button v-else class="_button" :class="$style.noteFooterButton" disabled> <button v-else class="_button" :class="$style.noteFooterButton" disabled>
<i class="ti ti-ban"></i> <i class="ti ti-ban"></i>
</button> </button>
<button v-if="appearNote.myReaction == null" ref="reactButton" :class="$style.noteFooterButton" class="_button" @mousedown="react()"> <button ref="reactButton" :class="$style.noteFooterButton" class="_button" @click="toggleReact()">
<i v-if="appearNote.reactionAcceptance === 'likeOnly'" class="ti ti-heart"></i> <i v-if="appearNote.reactionAcceptance === 'likeOnly' && appearNote.myReaction != null" class="ti ti-heart-filled" style="color: var(--eventReactionHeart);"></i>
<i v-else-if="appearNote.myReaction != null" class="ti ti-minus" style="color: var(--accent);"></i>
<i v-else-if="appearNote.reactionAcceptance === 'likeOnly'" class="ti ti-heart"></i>
<i v-else class="ti ti-plus"></i> <i v-else class="ti ti-plus"></i>
</button> <p v-if="(appearNote.reactionAcceptance === 'likeOnly' || defaultStore.state.showReactionsCount) && appearNote.reactionCount > 0" :class="$style.noteFooterButtonCount">{{ number(appearNote.reactionCount) }}</p>
<button v-if="appearNote.myReaction != null" ref="reactButton" class="_button" :class="[$style.noteFooterButton, $style.reacted]" @click="undoReact(appearNote)">
<i class="ti ti-minus"></i>
</button> </button>
<button v-if="defaultStore.state.showClipButtonInNoteFooter" ref="clipButton" class="_button" :class="$style.noteFooterButton" @mousedown="clip()"> <button v-if="defaultStore.state.showClipButtonInNoteFooter" ref="clipButton" class="_button" :class="$style.noteFooterButton" @mousedown="clip()">
<i class="ti ti-paperclip"></i> <i class="ti ti-paperclip"></i>
@ -209,6 +211,7 @@ import { pleaseLogin } from '@/scripts/please-login.js';
import { checkWordMute } from '@/scripts/check-word-mute.js'; import { checkWordMute } from '@/scripts/check-word-mute.js';
import { userPage } from '@/filters/user.js'; import { userPage } from '@/filters/user.js';
import { notePage } from '@/filters/note.js'; import { notePage } from '@/filters/note.js';
import number from '@/filters/number.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
import { misskeyApi } from '@/scripts/misskey-api.js'; import { misskeyApi } from '@/scripts/misskey-api.js';
import * as sound from '@/scripts/sound.js'; import * as sound from '@/scripts/sound.js';
@ -228,6 +231,7 @@ import MkUserCardMini from '@/components/MkUserCardMini.vue';
import MkPagination, { type Paging } from '@/components/MkPagination.vue'; import MkPagination, { type Paging } from '@/components/MkPagination.vue';
import MkReactionIcon from '@/components/MkReactionIcon.vue'; import MkReactionIcon from '@/components/MkReactionIcon.vue';
import MkButton from '@/components/MkButton.vue'; import MkButton from '@/components/MkButton.vue';
import { isEnabledUrlPreview } from '@/instance.js';
const props = defineProps<{ const props = defineProps<{
note: Misskey.entities.Note; note: Misskey.entities.Note;
@ -401,14 +405,22 @@ function react(viaKeyboard = false): void {
} }
} }
function undoReact(note): void { function undoReact(targetNote: Misskey.entities.Note): void {
const oldReaction = note.myReaction; const oldReaction = targetNote.myReaction;
if (!oldReaction) return; if (!oldReaction) return;
misskeyApi('notes/reactions/delete', { misskeyApi('notes/reactions/delete', {
noteId: note.id, noteId: targetNote.id,
}); });
} }
function toggleReact() {
if (appearNote.value.myReaction == null) {
react();
} else {
undoReact(appearNote.value);
}
}
function onContextmenu(ev: MouseEvent): void { function onContextmenu(ev: MouseEvent): void {
const isLink = (el: HTMLElement): boolean => { const isLink = (el: HTMLElement): boolean => {
if (el.tagName === 'A') return true; if (el.tagName === 'A') return true;

View File

@ -8,6 +8,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<div :class="$style.head"> <div :class="$style.head">
<MkAvatar v-if="['pollEnded', 'note'].includes(notification.type) && notification.note" :class="$style.icon" :user="notification.note.user" link preview/> <MkAvatar v-if="['pollEnded', 'note'].includes(notification.type) && notification.note" :class="$style.icon" :user="notification.note.user" link preview/>
<MkAvatar v-else-if="['roleAssigned', 'achievementEarned'].includes(notification.type)" :class="$style.icon" :user="$i" link preview/> <MkAvatar v-else-if="['roleAssigned', 'achievementEarned'].includes(notification.type)" :class="$style.icon" :user="$i" link preview/>
<div v-else-if="notification.type === 'reaction:grouped' && notification.note.reactionAcceptance === 'likeOnly'" :class="[$style.icon, $style.icon_reactionGroupHeart]"><i class="ti ti-heart" style="line-height: 1;"></i></div>
<div v-else-if="notification.type === 'reaction:grouped'" :class="[$style.icon, $style.icon_reactionGroup]"><i class="ti ti-plus" style="line-height: 1;"></i></div> <div v-else-if="notification.type === 'reaction:grouped'" :class="[$style.icon, $style.icon_reactionGroup]"><i class="ti ti-plus" style="line-height: 1;"></i></div>
<div v-else-if="notification.type === 'renote:grouped'" :class="[$style.icon, $style.icon_renoteGroup]"><i class="ti ti-repeat" style="line-height: 1;"></i></div> <div v-else-if="notification.type === 'renote:grouped'" :class="[$style.icon, $style.icon_renoteGroup]"><i class="ti ti-repeat" style="line-height: 1;"></i></div>
<img v-else-if="notification.type === 'test'" :class="$style.icon" :src="infoImageUrl"/> <img v-else-if="notification.type === 'test'" :class="$style.icon" :src="infoImageUrl"/>
@ -57,6 +58,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<span v-else-if="notification.type === 'achievementEarned'">{{ i18n.ts._notification.achievementEarned }}</span> <span v-else-if="notification.type === 'achievementEarned'">{{ i18n.ts._notification.achievementEarned }}</span>
<span v-else-if="notification.type === 'test'">{{ i18n.ts._notification.testNotification }}</span> <span v-else-if="notification.type === 'test'">{{ i18n.ts._notification.testNotification }}</span>
<MkA v-else-if="notification.type === 'follow' || notification.type === 'mention' || notification.type === 'reply' || notification.type === 'renote' || notification.type === 'quote' || notification.type === 'reaction' || notification.type === 'receiveFollowRequest' || notification.type === 'followRequestAccepted'" v-user-preview="notification.user.id" :class="$style.headerName" :to="userPage(notification.user)"><MkUserName :user="notification.user"/></MkA> <MkA v-else-if="notification.type === 'follow' || notification.type === 'mention' || notification.type === 'reply' || notification.type === 'renote' || notification.type === 'quote' || notification.type === 'reaction' || notification.type === 'receiveFollowRequest' || notification.type === 'followRequestAccepted'" v-user-preview="notification.user.id" :class="$style.headerName" :to="userPage(notification.user)"><MkUserName :user="notification.user"/></MkA>
<span v-else-if="notification.type === 'reaction:grouped' && notification.note.reactionAcceptance === 'likeOnly'">{{ i18n.tsx._notification.likedBySomeUsers({ n: notification.reactions.length }) }}</span>
<span v-else-if="notification.type === 'reaction:grouped'">{{ i18n.tsx._notification.reactedBySomeUsers({ n: notification.reactions.length }) }}</span> <span v-else-if="notification.type === 'reaction:grouped'">{{ i18n.tsx._notification.reactedBySomeUsers({ n: notification.reactions.length }) }}</span>
<span v-else-if="notification.type === 'renote:grouped'">{{ i18n.tsx._notification.renotedBySomeUsers({ n: notification.users.length }) }}</span> <span v-else-if="notification.type === 'renote:grouped'">{{ i18n.tsx._notification.renotedBySomeUsers({ n: notification.users.length }) }}</span>
<span v-else-if="notification.type === 'app'">{{ notification.header }}</span> <span v-else-if="notification.type === 'app'">{{ notification.header }}</span>
@ -201,6 +203,7 @@ const rejectFollowRequest = () => {
} }
.icon_reactionGroup, .icon_reactionGroup,
.icon_reactionGroupHeart,
.icon_renoteGroup { .icon_renoteGroup {
display: grid; display: grid;
align-items: center; align-items: center;
@ -213,11 +216,15 @@ const rejectFollowRequest = () => {
} }
.icon_reactionGroup { .icon_reactionGroup {
background: #e99a0b; background: var(--eventReaction);
}
.icon_reactionGroupHeart {
background: var(--eventReactionHeart);
} }
.icon_renoteGroup { .icon_renoteGroup {
background: #36d298; background: var(--eventRenote);
} }
.icon_app { .icon_app {
@ -246,49 +253,49 @@ const rejectFollowRequest = () => {
.t_follow, .t_followRequestAccepted, .t_receiveFollowRequest { .t_follow, .t_followRequestAccepted, .t_receiveFollowRequest {
padding: 3px; padding: 3px;
background: #36aed2; background: var(--eventFollow);
pointer-events: none; pointer-events: none;
} }
.t_renote { .t_renote {
padding: 3px; padding: 3px;
background: #36d298; background: var(--eventRenote);
pointer-events: none; pointer-events: none;
} }
.t_quote { .t_quote {
padding: 3px; padding: 3px;
background: #36d298; background: var(--eventRenote);
pointer-events: none; pointer-events: none;
} }
.t_reply { .t_reply {
padding: 3px; padding: 3px;
background: #007aff; background: var(--eventReply);
pointer-events: none; pointer-events: none;
} }
.t_mention { .t_mention {
padding: 3px; padding: 3px;
background: #88a6b7; background: var(--eventOther);
pointer-events: none; pointer-events: none;
} }
.t_pollEnded { .t_pollEnded {
padding: 3px; padding: 3px;
background: #88a6b7; background: var(--eventOther);
pointer-events: none; pointer-events: none;
} }
.t_achievementEarned { .t_achievementEarned {
padding: 3px; padding: 3px;
background: #cb9a11; background: var(--eventAchievement);
pointer-events: none; pointer-events: none;
} }
.t_roleAssigned { .t_roleAssigned {
padding: 3px; padding: 3px;
background: #88a6b7; background: var(--eventOther);
pointer-events: none; pointer-events: none;
} }

View File

@ -19,18 +19,21 @@ SPDX-License-Identifier: AGPL-3.0-only
<div style="margin-top: 16px;">{{ i18n.ts.authenticationRequiredToContinue }}</div> <div style="margin-top: 16px;">{{ i18n.ts.authenticationRequiredToContinue }}</div>
</div> </div>
<div class="_gaps"> <form @submit.prevent="done">
<MkInput ref="passwordInput" v-model="password" :placeholder="i18n.ts.password" type="password" autocomplete="current-password webauthn" :withPasswordToggle="true"> <div class="_gaps">
<template #prefix><i class="ti ti-password"></i></template> <MkInput ref="passwordInput" v-model="password" :placeholder="i18n.ts.password" type="password" autocomplete="current-password webauthn" required :withPasswordToggle="true">
</MkInput> <template #prefix><i class="ti ti-password"></i></template>
</MkInput>
<MkInput v-if="$i.twoFactorEnabled" v-model="token" type="text" pattern="^([0-9]{6}|[A-Z0-9]{32})$" autocomplete="one-time-code" :spellcheck="false"> <MkInput v-if="$i.twoFactorEnabled" v-model="token" type="text" :pattern="isBackupCode ? '^[A-Z0-9]{32}$' :'^[0-9]{6}$'" autocomplete="one-time-code" required :spellcheck="false" :inputmode="isBackupCode ? undefined : 'numeric'">
<template #label>{{ i18n.ts.token }} ({{ i18n.ts['2fa'] }})</template> <template #label>{{ i18n.ts.token }} ({{ i18n.ts['2fa'] }})</template>
<template #prefix><i class="ti ti-123"></i></template> <template #prefix><i v-if="isBackupCode" class="ti ti-key"></i><i v-else class="ti ti-123"></i></template>
</MkInput> <template #caption><button class="_textButton" type="button" @click="isBackupCode = !isBackupCode">{{ isBackupCode ? i18n.ts.useTotp : i18n.ts.useBackupCode }}</button></template>
</MkInput>
<MkButton :disabled="(password ?? '') == '' || ($i.twoFactorEnabled && (token ?? '') == '')" primary rounded style="margin: 0 auto;" @click="done"><i class="ti ti-lock-open"></i> {{ i18n.ts.continue }}</MkButton> <MkButton :disabled="(password ?? '') == '' || ($i.twoFactorEnabled && (token ?? '') == '')" type="submit" primary rounded style="margin: 0 auto;"><i class="ti ti-lock-open"></i> {{ i18n.ts.continue }}</MkButton>
</div> </div>
</form>
</MkSpacer> </MkSpacer>
</MkModalWindow> </MkModalWindow>
</template> </template>
@ -54,6 +57,7 @@ const emit = defineEmits<{
const dialog = shallowRef<InstanceType<typeof MkModalWindow>>(); const dialog = shallowRef<InstanceType<typeof MkModalWindow>>();
const passwordInput = shallowRef<InstanceType<typeof MkInput>>(); const passwordInput = shallowRef<InstanceType<typeof MkInput>>();
const password = ref(''); const password = ref('');
const isBackupCode = ref(false);
const token = ref<string | null>(null); const token = ref<string | null>(null);
function onClose() { function onClose() {
@ -61,7 +65,7 @@ function onClose() {
if (dialog.value) dialog.value.close(); if (dialog.value) dialog.value.close();
} }
function done(res) { function done() {
emit('done', { password: password.value, token: token.value }); emit('done', { password: password.value, token: token.value });
if (dialog.value) dialog.value.close(); if (dialog.value) dialog.value.close();
} }

View File

@ -31,15 +31,15 @@ SPDX-License-Identifier: AGPL-3.0-only
<div v-if="user && user.securityKeys" class="or-hr"> <div v-if="user && user.securityKeys" class="or-hr">
<p class="or-msg">{{ i18n.ts.or }}</p> <p class="or-msg">{{ i18n.ts.or }}</p>
</div> </div>
<div class="twofa-group totp-group"> <div class="twofa-group totp-group _gaps">
<p style="margin-bottom:0;">{{ i18n.ts['2fa'] }}</p>
<MkInput v-if="user && user.usePasswordLessLogin" v-model="password" type="password" autocomplete="current-password" :withPasswordToggle="true" required> <MkInput v-if="user && user.usePasswordLessLogin" v-model="password" type="password" autocomplete="current-password" :withPasswordToggle="true" required>
<template #label>{{ i18n.ts.password }}</template> <template #label>{{ i18n.ts.password }}</template>
<template #prefix><i class="ti ti-lock"></i></template> <template #prefix><i class="ti ti-lock"></i></template>
</MkInput> </MkInput>
<MkInput v-model="token" type="text" pattern="^([0-9]{6}|[A-Z0-9]{32})$" autocomplete="one-time-code" :spellcheck="false" required> <MkInput v-model="token" type="text" :pattern="isBackupCode ? '^[A-Z0-9]{32}$' :'^[0-9]{6}$'" autocomplete="one-time-code" required :spellcheck="false" :inputmode="isBackupCode ? undefined : 'numeric'">
<template #label>{{ i18n.ts.token }}</template> <template #label>{{ i18n.ts.token }} ({{ i18n.ts['2fa'] }})</template>
<template #prefix><i class="ti ti-123"></i></template> <template #prefix><i v-if="isBackupCode" class="ti ti-key"></i><i v-else class="ti ti-123"></i></template>
<template #caption><button class="_textButton" type="button" @click="isBackupCode = !isBackupCode">{{ isBackupCode ? i18n.ts.useTotp : i18n.ts.useBackupCode }}</button></template>
</MkInput> </MkInput>
<MkButton type="submit" :disabled="signing" large primary rounded style="margin: 0 auto;">{{ signing ? i18n.ts.loggingIn : i18n.ts.login }}</MkButton> <MkButton type="submit" :disabled="signing" large primary rounded style="margin: 0 auto;">{{ signing ? i18n.ts.loggingIn : i18n.ts.login }}</MkButton>
</div> </div>
@ -70,6 +70,7 @@ const password = ref('');
const token = ref(''); const token = ref('');
const host = ref(toUnicode(configHost)); const host = ref(toUnicode(configHost));
const totpLogin = ref(false); const totpLogin = ref(false);
const isBackupCode = ref(false);
const queryingKey = ref(false); const queryingKey = ref(false);
const credentialRequest = ref<CredentialRequestOptions | null>(null); const credentialRequest = ref<CredentialRequestOptions | null>(null);

View File

@ -63,6 +63,7 @@ const exampleNote = reactive<Misskey.entities.Note>({
reactionAcceptance: null, reactionAcceptance: null,
renoteCount: 0, renoteCount: 0,
repliesCount: 1, repliesCount: 1,
reactionCount: 0,
reactions: {}, reactions: {},
reactionEmojis: {}, reactionEmojis: {},
fileIds: [], fileIds: [],

View File

@ -68,6 +68,7 @@ const exampleCWNote = reactive<Misskey.entities.Note>({
reactionAcceptance: null, reactionAcceptance: null,
renoteCount: 0, renoteCount: 0,
repliesCount: 1, repliesCount: 1,
reactionCount: 0,
reactions: {}, reactions: {},
reactionEmojis: {}, reactionEmojis: {},
fileIds: [], fileIds: [],

View File

@ -58,6 +58,7 @@ const exampleNote = reactive<Misskey.entities.Note>({
reactionAcceptance: null, reactionAcceptance: null,
renoteCount: 0, renoteCount: 0,
repliesCount: 1, repliesCount: 1,
reactionCount: 0,
reactions: {}, reactions: {},
reactionEmojis: {}, reactionEmojis: {},
fileIds: ['0000000002'], fileIds: ['0000000002'],

View File

@ -152,15 +152,16 @@ requestUrl.hash = '';
window.fetch(`/url?url=${encodeURIComponent(requestUrl.href)}&lang=${versatileLang}`) window.fetch(`/url?url=${encodeURIComponent(requestUrl.href)}&lang=${versatileLang}`)
.then(res => { .then(res => {
if (!res.ok) { if (!res.ok) {
fetching.value = false; if (_DEV_) {
unknownUrl.value = true; console.warn(`[HTTP${res.status}] Failed to fetch url preview`);
return; }
return null;
} }
return res.json(); return res.json();
}) })
.then((info: SummalyResult) => { .then((info: SummalyResult | null) => {
if (info.url == null) { if (!info || info.url == null) {
fetching.value = false; fetching.value = false;
unknownUrl.value = true; unknownUrl.value = true;
return; return;

View File

@ -1,3 +1,8 @@
<!--
SPDX-FileCopyrightText: syuilo and misskey-project
SPDX-License-Identifier: AGPL-3.0-only
-->
<template> <template>
<render/> <render/>
</template> </template>

View File

@ -4,13 +4,13 @@ SPDX-License-Identifier: AGPL-3.0-only
--> -->
<template> <template>
<a :href="to" :class="active ? activeClass : null" @click.prevent="nav" @contextmenu.prevent.stop="onContextmenu"> <a ref="el" :href="to" :class="active ? activeClass : null" @click.prevent="nav" @contextmenu.prevent.stop="onContextmenu">
<slot></slot> <slot></slot>
</a> </a>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue'; import { computed, shallowRef } from 'vue';
import * as os from '@/os.js'; import * as os from '@/os.js';
import copyToClipboard from '@/scripts/copy-to-clipboard.js'; import copyToClipboard from '@/scripts/copy-to-clipboard.js';
import { url } from '@/config.js'; import { url } from '@/config.js';
@ -26,6 +26,10 @@ const props = withDefaults(defineProps<{
behavior: null, behavior: null,
}); });
const el = shallowRef<HTMLElement>();
defineExpose({ $el: el });
const router = useRouter(); const router = useRouter();
const active = computed(() => { const active = computed(() => {

View File

@ -14,10 +14,20 @@ SPDX-License-Identifier: AGPL-3.0-only
[$style.form_vertical]: chosen.place === 'vertical', [$style.form_vertical]: chosen.place === 'vertical',
}]" }]"
> >
<a :href="chosen.url" target="_blank" :class="$style.link"> <component
:is="self ? 'MkA' : 'a'"
:class="$style.link"
v-bind="self ? {
to: chosen.url.substring(local.length),
} : {
href: chosen.url,
rel: 'nofollow noopener',
target: '_blank',
}"
>
<img :src="chosen.imageUrl" :class="$style.img"> <img :src="chosen.imageUrl" :class="$style.img">
<button class="_button" :class="$style.i" @click.prevent.stop="toggleMenu"><i :class="$style.iIcon" class="ti ti-info-circle"></i></button> <button class="_button" :class="$style.i" @click.prevent.stop="toggleMenu"><i :class="$style.iIcon" class="ti ti-info-circle"></i></button>
</a> </component>
</div> </div>
<div v-else :class="$style.menu"> <div v-else :class="$style.menu">
<div :class="$style.menuContainer"> <div :class="$style.menuContainer">
@ -32,10 +42,10 @@ SPDX-License-Identifier: AGPL-3.0-only
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue'; import { ref, computed } from 'vue';
import { i18n } from '@/i18n.js'; import { i18n } from '@/i18n.js';
import { instance } from '@/instance.js'; import { instance } from '@/instance.js';
import { host } from '@/config.js'; import { url as local, host } from '@/config.js';
import MkButton from '@/components/MkButton.vue'; import MkButton from '@/components/MkButton.vue';
import { defaultStore } from '@/store.js'; import { defaultStore } from '@/store.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
@ -96,6 +106,9 @@ const choseAd = (): Ad | null => {
}; };
const chosen = ref(choseAd()); const chosen = ref(choseAd());
const self = computed(() => chosen.value?.url.startsWith(local));
const shouldHide = ref(!defaultStore.state.forceShowAds && $i && $i.policies.canHideAds && (props.specify == null)); const shouldHide = ref(!defaultStore.state.forceShowAds && $i && $i.policies.canHideAds && (props.specify == null));
function reduceFrequency(): void { function reduceFrequency(): void {

View File

@ -30,6 +30,7 @@ import { url as local } from '@/config.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
import { useTooltip } from '@/scripts/use-tooltip.js'; import { useTooltip } from '@/scripts/use-tooltip.js';
import { safeURIDecode } from '@/scripts/safe-uri-decode.js'; import { safeURIDecode } from '@/scripts/safe-uri-decode.js';
import { isEnabledUrlPreview } from '@/instance.js';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
url: string; url: string;
@ -44,12 +45,12 @@ const url = new URL(props.url);
if (!['http:', 'https:'].includes(url.protocol)) throw new Error('invalid url'); if (!['http:', 'https:'].includes(url.protocol)) throw new Error('invalid url');
const el = ref(); const el = ref();
if (props.showUrlPreview) { if (props.showUrlPreview && isEnabledUrlPreview.value) {
useTooltip(el, (showing) => { useTooltip(el, (showing) => {
os.popup(defineAsyncComponent(() => import('@/components/MkUrlPreviewPopup.vue')), { os.popup(defineAsyncComponent(() => import('@/components/MkUrlPreviewPopup.vue')), {
showing, showing,
url: props.url, url: props.url,
source: el.value, source: el.value instanceof HTMLElement ? el.value : el.value?.$el,
}, {}, 'closed'); }, {}, 'closed');
}); });
} }

View File

@ -4,19 +4,15 @@ SPDX-License-Identifier: AGPL-3.0-only
--> -->
<template> <template>
<div> <div :class="$style.root">
<MediaImage <MkMediaList v-if="image" :mediaList="[image]" :class="$style.mediaList"/>
v-if="image"
:image="image"
:disableImageLink="true"
/>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue';
import * as Misskey from 'misskey-js'; import * as Misskey from 'misskey-js';
import MediaImage from '@/components/MkMediaImage.vue'; import MkMediaList from '@/components/MkMediaList.vue';
const props = defineProps<{ const props = defineProps<{
block: Misskey.entities.PageBlock, block: Misskey.entities.PageBlock,
@ -28,5 +24,17 @@ const image = ref<Misskey.entities.DriveFile | null>(null);
onMounted(() => { onMounted(() => {
image.value = props.page.attachedFiles.find(x => x.id === props.block.fileId) ?? null; image.value = props.page.attachedFiles.find(x => x.id === props.block.fileId) ?? null;
}); });
</script> </script>
<style lang="scss" module>
.root {
border: 1px solid var(--divider);
border-radius: var(--radius);
overflow: hidden;
}
.mediaList {
// MkMediaList 4px
margin-top: -4px;
height: calc(100% + 4px);
}
</style>

View File

@ -4,9 +4,9 @@ SPDX-License-Identifier: AGPL-3.0-only
--> -->
<template> <template>
<div style="margin: 1em 0;"> <div :class="$style.root">
<MkNote v-if="note && !block.detailed" :key="note.id + ':normal'" v-model:note="note"/> <MkNote v-if="note && !block.detailed" :key="note.id + ':normal'" :note="note"/>
<MkNoteDetailed v-if="note && block.detailed" :key="note.id + ':detail'" v-model:note="note"/> <MkNoteDetailed v-if="note && block.detailed" :key="note.id + ':detail'" :note="note"/>
</div> </div>
</template> </template>
@ -32,3 +32,10 @@ onMounted(() => {
}); });
}); });
</script> </script>
<style lang="scss" module>
.root {
border: 1px solid var(--divider);
border-radius: var(--radius);
}
</style>

Some files were not shown because too many files have changed in this diff Show More